[英]How to set attribute of select option by targeting value instead of index
When a user clicks on a particular div (in my case a palette of swatches) I need that click to set the "selected" attribute of an option in a select list to "selected". 当用户单击特定的div(在我的情况下是色板)时,我需要单击以将选择列表中选项的“ selected”属性设置为“ selected”。 This is working when I can target the option by its index with something like this: 当我可以通过类似以下内容的索引将选项作为目标时,此方法有效:
onClick="getElementById('the_select')
.options[2].setAttribute('selected', 'selected');"
But this doesn't work when I try to target the option by its value like this: 但是,当我尝试通过如下所示的选项值来定位选项时,这种方法不起作用:
onClick="getElementById('the_select')
.option[value='blue'].setAttribute('selected', 'selected');"
I need to target the value because in this case "blue" is not always going to be in the same place in the select list. 我需要确定目标值,因为在这种情况下,“蓝色”并不总是会出现在选择列表中的同一位置。
How can I accomplish this? 我该怎么做?
我猜你可以做这样的事情:
document.getElementById("my_select").selected=true;
I found a workable solution using straight javascript based on a post by Dave on this thread... 我基于Dave在此线程上发表的帖子,使用直接的javascript找到了可行的解决方案...
jQuery - setting the selected value of a select control via its text description jQuery-通过文本说明设置选择控件的选择值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.