jquery - 动态更改选项文本不起作用
jquery - dynamically changing the option text is not working
请找到 jsfiddle
https://jsfiddle.net/qs008so7/
我在 html 中有一个选项框,我正在尝试使用 jquery 设置该选项。
但它不起作用。请在下面找到代码。
如果我在控制台中调用代码,我能够看到预期的 html 正在返回。 意味着,更改会在 DOM 中受到适当影响,但不会反映在 UI. 中。你可以看看我的 jfiddle .
HTML:
<select class="form-control" name="test" id="test">
<option value="0">Disabled</option>
<option value="1">Enabled</option>
</select>
JS:
setGivenOption(test,"Enabled");
setGivenOption(test,"Disabled");
function setGivenOption(elementId, option) {
//Make all the old selections to null
$(elementId).each(function () {
$('option', this).each(function () {
$(this).attr('selected', null);
});
});
//set the given option
$(elementId).find(">option:contains('" + option + "')").attr("selected", "selected");
}
谢谢。
你快到了:像这样试试https://jsfiddle.net/q5886d5o/1/
在@Chips_100评论
后更新
setGivenOption("test","Disabled");
setGivenOption("test","Enabled");
function setGivenOption(elementId, option) {
//Make all the old selections to null
$('#' + elementId).children('option').each(function () {
$(this).attr('selected', null);
});
//set the given option
$('#' + elementId).children("option:contains('" + option + "')").attr("selected", "selected");
}
简化
$(elementId).find('option:contains(' + option + ')').attr('selected', true);
那会做select 任何 selected 和 select 新的 option
请找到 jsfiddle
https://jsfiddle.net/qs008so7/
我在 html 中有一个选项框,我正在尝试使用 jquery 设置该选项。 但它不起作用。请在下面找到代码。
如果我在控制台中调用代码,我能够看到预期的 html 正在返回。 意味着,更改会在 DOM 中受到适当影响,但不会反映在 UI. 中。你可以看看我的 jfiddle .
HTML:
<select class="form-control" name="test" id="test">
<option value="0">Disabled</option>
<option value="1">Enabled</option>
</select>
JS:
setGivenOption(test,"Enabled");
setGivenOption(test,"Disabled");
function setGivenOption(elementId, option) {
//Make all the old selections to null
$(elementId).each(function () {
$('option', this).each(function () {
$(this).attr('selected', null);
});
});
//set the given option
$(elementId).find(">option:contains('" + option + "')").attr("selected", "selected");
}
谢谢。
你快到了:像这样试试https://jsfiddle.net/q5886d5o/1/
在@Chips_100评论
后更新setGivenOption("test","Disabled");
setGivenOption("test","Enabled");
function setGivenOption(elementId, option) {
//Make all the old selections to null
$('#' + elementId).children('option').each(function () {
$(this).attr('selected', null);
});
//set the given option
$('#' + elementId).children("option:contains('" + option + "')").attr("selected", "selected");
}
简化
$(elementId).find('option:contains(' + option + ')').attr('selected', true);
那会做select 任何 selected 和 select 新的 option