首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在jQuery中应用“选定”元素?

如何在jQuery中应用“选定”元素?
EN

Stack Overflow用户
提问于 2019-11-08 12:35:53
回答 2查看 58关注 0票数 0

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

HTML中的示例

代码语言:javascript
运行
复制
<select id="threshold">
    <option value="90" selected>90</option>   /* example selected in HTML */
</select>

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

代码语言:javascript
运行
复制
$("#threshold").append($("<option>",{value: "70",text: "70%"}));
$("#threshold").append($("<option>",{value: "80",text: "80%"}));
$("#threshold").append($("<option>",{value: "90",text: "90%"}));
EN

回答 2

Stack Overflow用户

发布于 2019-11-08 12:43:39

任一

代码语言:javascript
运行
复制
$("#threshold").append($("<option>",{ value: "90",text: "90%", selected:true }));

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

代码语言:javascript
运行
复制
$("#threshold")
  .append($("<option>",{value: "90",text: "90%"}))
  .val("90");

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

较短:

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

票数 1
EN

Stack Overflow用户

发布于 2019-11-08 12:43:20

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

代码语言:javascript
运行
复制
const options = [
   {value: "70",text: "70%"}
  ,{value: "80",text: "80%"}
  ,{value: "90",text: "90%", selected: true}
];

$("#threshold").append(options.map(o => $("<option>", o)));
代码语言:javascript
运行
复制
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select id="threshold"></select>

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/58766718

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档