如何在jQuery中应用"selected"元素?



我想将数字90作为默认值。有人知道如何将下面HTML中的selected元素应用到jQuery中吗?

HTML中的示例

<select id="threshold">
<option value="90" selected>90</option>   /* example selected in HTML */
</select>

如何在jQuery中应用selected,以数字90作为默认值?

$("#threshold").append($("<option>",{value: "70",text: "70%"}));
$("#threshold").append($("<option>",{value: "80",text: "80%"}));
$("#threshold").append($("<option>",{value: "90",text: "90%"}));

任一

$("#threshold").append($("<option>",{ value: "90",text: "90%", selected:true }));

$("#threshold")
.append($("<option>",{value: "70",text: "70%"}))
.append($("<option>",{value: "80",text: "80%"}))
.append($("<option>",{value: "90",text: "90%", selected:true }))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="threshold">
</select>

$("#threshold")
.append($("<option>",{value: "90",text: "90%"}))
.val("90");

$("#threshold")
.append($("<option>",{value: "70",text: "70%"}))
.append($("<option>",{value: "80",text: "80%"}))
.append($("<option>",{value: "90",text: "90%"}))
.val(90);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="threshold">
</select>

较短:

const curTH = 90;
$.each([70, 80, 90], (_, item) =>
$("<option>",{ value: item, text: item + "%", "selected": item === curTH ? true : false })
.appendTo("#threshold")
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="threshold">
</select>

只需通过在对象中添加selected: true来告诉jQuery应该选择哪一个

const options = [
{value: "70",text: "70%"}
,{value: "80",text: "80%"}
,{value: "90",text: "90%", selected: true}
];
$("#threshold").append(options.map(o => $("<option>", o)));
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="threshold"></select>

最新更新