jQuery/以编程方式在“选择"框中选择一个选项

编程入门 行业动态 更新时间:2024-10-19 02:19:06
本文介绍了jQuery/以编程方式在“选择"框中选择一个选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我目前正在使用jQuery返回一些JSON结果.返回这些结果后,我将使用它们来预填充表单中的字段.

I'm currently using jQuery to return some JSON results. Once these results are returned, I'm using them to pre-populate fields in my form.

但是,在下拉框中预选项目时,我需要一些帮助.例如,我有一个选择框(缩短了):

However, I need some help in pre-selecting items in a drop down box. For example, I have a select box (this is shortened):

<select id="startTime"> <option value="14:00:00">2:00 pm</option> <option value="15:00:00">3:00 pm</option> <option value="16:00:00">4:00 pm</option> <option value="17:00:00">5:00 pm</option> <option value="18:00:00">6:00 pm</option> </select>

如果我的JSON值为:

And if my JSON value is:

var start_time = data[0].start // Let's say this is '17:00:00'

我如何使用jQuery将选项设置为'17:00:00'?

How can I, using jQuery, make the option with value '17:00:00' selected?

<option value="17:00:00" selected="selected">5:00 pm</option>

推荐答案

更新:

从jQuery 1.9开始,jQuery已更新,更改了此功能.选项的选择"状态实际上是一个属性,因此jQuery将其更改为使用.prop()方法.语法非常相似且易于切换:

As of jQuery 1.9, jQuery has updated changed this functionality. The "selected" state of an option is actually a property, therefore jQuery has changed this to use the .prop() method. Syntax is very similar and easy to switch:

$('#startTime option[value=17:00:00]').prop('selected', true);

请参见 api.jquery/prop/#entry-longdesc为什么需要通过true.

See api.jquery/prop/#entry-longdesc for why it needs to pass true.

旧版jQuery

$('#startTime option[value=17:00:00]').attr('selected', 'selected');

$('#startTime option[value='+ data[0].start +']').attr('selected', 'selected');

更多推荐

jQuery/以编程方式在“选择"框中选择一个选项

本文发布于:2023-11-24 20:54:29,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1626776.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:框中   选项   方式   jQuery   quot

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!