如何将 select 的选项更改为 jQuery?

How can I change the option of a select with jQuery?

我正在使用 BuddyPress 插件在用户配置文件中创建一个多 select 选项。不幸的是,在人们点击这个 select 之前,显示的文字是“----”。我想使用 jquery 将显示文本从“----”更改为 'Please select' 之类的内容。我怎样才能在 jQuery 中做到这一点?

<select id="field_221" name="field_221" aria-required="true">
    <option value="">----</option>
    <option value="13">13</option>
    <option> value="14">14</option>
    <option> value="15">15</option>
</select>

您可以通过遍历 select 选项并替换任何等于“----”的选项来完成此操作。

JavaScript:

$(function () { // Executes on DOM ready
    $("#field_221 > option").each(function () {
        if (this.text === '----') {
            this.text = 'Please select';
        }
    });
});

演示http://jsfiddle.net/BenjaminRay/8r3d9r9c/

此外,您在最后两个选项中多了一个>。将 <option> value... 更改为 <option value...