我想将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%"}));
答案 0 :(得分:1)
任何一个
$("#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>
答案 1 :(得分:0)
只要告诉jQuery应该通过在对象中添加selected: true
来选择哪个
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>