[英]jquery - dynamically changing the option text is not working
請找到jsfiddle
https://jsfiddle.net/qs008so7/
我在html中有一個選項框,我正在嘗試使用jquery設置選項。 但是它不起作用。 請在下面找到代碼。
如果我在控制台中調用該代碼,並且能夠看到預期的html返回了。 意味着,這些更改會在DOM中受到適當影響,但不會在UI中反映出來。 。 你可以看到我的小提琴。
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);
這將雙選所選擇的內容並選擇新option
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.