【发布时间】:2017-11-14 22:07:48
【问题描述】:
在我的代码中,我清空了一个 <select> 元素并使用可用时间再次重建它。
但是,如果 <option> 与之前选择的时间匹配,我会尝试将其设置为选中:
if(time == currenttime) {
console.log("Matched Time "+currenttime);
$("#time-start").append($("<option></option>").attr("value", time).text(time)).prop("selected","selected");
} else {
$("#time-start").append($("<option></option>").attr("value", time).text(time));
}
我收到控制台消息Matched Time,但.prop("selected","selected") 没有设置要选择的新创建选项。
如何设置为选中?
【问题讨论】:
-
您将
.prop()链接到.append()调用,.append()返回原始链接的 jQuery 对象,而不是附加的元素。因此,您实际上是在尝试在<select>元素而不是<option>元素上设置“已选择”。 -
先附加所有选项,然后调用
$('#time-start').val(time)
标签: javascript jquery