【问题标题】:How to set attribute of select option by targeting value instead of index如何通过定位值而不是索引来设置选择选项的属性
【发布时间】:2014-10-15 14:18:44
【问题描述】:

当用户单击特定的 div(在我的情况下是色板调色板)时,我需要单击以将选择列表中选项的“已选择”属性设置为“已选择”。当我可以通过它的索引来定位选项时,这是有效的:

onClick="getElementById('the_select')
         .options[2].setAttribute('selected', 'selected');"

但是当我尝试通过它的值来定位选项时,这不起作用:

 onClick="getElementById('the_select')
         .option[value='blue'].setAttribute('selected', 'selected');"

我需要定位该值,因为在这种情况下,“蓝色”并不总是在选择列表中的相同位置。

我怎样才能做到这一点?

【问题讨论】:

  • the_select.value="blue";效果很好,不要让它过于复杂。
  • @gibsonman507 jQuery 是一种可能。
  • @dandavis 我希望它这么简单,但为了让购物车识别出已做出选择,我似乎需要为该选项设置“已选择”属性。

标签: javascript select attributes option


【解决方案1】:

我根据 Dave 在此线程上的帖子找到了一个使用直接 javascript 的可行解决方案...

jQuery - setting the selected value of a select control via its text description

【讨论】:

    【解决方案2】:

    我猜你可以这样做:

    document.getElementById("my_select").selected=true;
    

    【讨论】:

    • 我尝试了类似的方法,但由于某种原因,我们的购物车系统希望设置“已选择”属性,否则它不会认为用户实际上选择了任何东西。
    猜你喜欢
    • 2013-02-14
    • 1970-01-01
    • 1970-01-01
    • 2015-05-14
    • 2017-01-10
    • 1970-01-01
    • 2011-08-06
    • 2021-03-08
    • 1970-01-01
    相关资源
    最近更新 更多