【问题标题】:When appending an <option></option> in jQuery, how to set selected?在 jQuery 中附加 <option></option> 时,如何设置选中?
【发布时间】:2017-11-14 22:07:48
【问题描述】:

在我的代码中,我清空了一个 &lt;select&gt; 元素并使用可用时间再次重建它。

但是,如果 &lt;option&gt; 与之前选择的时间匹配,我会尝试将其设置为选中:

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 对象,而不是附加的元素。因此,您实际上是在尝试在 &lt;select&gt; 元素而不是 &lt;option&gt; 元素上设置“已选择”。
  • 先附加所有选项,然后调用$('#time-start').val(time)

标签: javascript jquery


【解决方案1】:

我认为您的代码会像这样变得更具可读性(从而更容易在正确的位置设置 selected 属性):

let $opt = $("<option></option>").attr("value", time).text(time);
if(time == currenttime) {
    console.log("Matched Time "+currenttime);
    $opt.prop("selected","selected");
}
$("#time-start").append($opt);

【讨论】:

  • 行得通!只是为了让我学习,这与我上面做的内联设置有什么不同?
  • @Chud37 看看你的括号。在您的代码中,您在#time-start 元素上设置selected 属性,而不是在&lt;option&gt; 上。
【解决方案2】:

你很接近,将selected 设置为option 元素

var option = $("<option>", {"selected" : time == currenttime, text: time, value: time });
$("#time-start").append(option );

或者,使用.val()

$("#time-start").val(time)

【讨论】:

    【解决方案3】:

    改成如下:

    $("#time-start").append($("<option></option>").prop("selected",true).attr("value", time).text(time));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-28
      • 2014-07-25
      • 2020-07-27
      • 1970-01-01
      • 1970-01-01
      • 2016-03-01
      • 2013-05-21
      相关资源
      最近更新 更多