在我的代码中,我清空了一个<select>
元素,并用可用时间重新构建它。在jQuery中追加<option></option>时,如何设置选中?
但是我想设置<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对象,而不是附加的元素。所以你实际上试图在“
追加所有选项,然后调用'$('#time-start')。val(time)' –