如何使用 Jquery 更改选项值?

2024-03-22

我正在寻找一种在用户单击链接时更改选择标记的选项值的方法。

例如我有一个选择选项 html:

<select> <option value="0">Please Select</option> 
<option value="1">red</option> 
<option value="2">white</option> 
</select>

我有2个链接<a href="#" title="red" class="preview_link">red</a> <a href="#" title="white">white</a>当用户单击红色时,选项将切换为红色,白色将切换为白色。我正在使用以下代码,但它不起作用。

 jQuery("a.preview_link").click(function() {
    var title = jQuery(this).attr("title");
        jQuery(this).parent('p').children("select :selected").text(title);
 });

有什么建议么?


您的方式会将选项的文本设置为标题属性。尝试:

 jQuery("a.preview_link").click(function() {
    var title = jQuery(this).attr("title");
    jQuery(this).parent('p').find("select option").filter(function() {
        return $(this).text() == title;
    }).attr('selected', 'selected');
 });

See filter http://api.jquery.com/filter/.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 Jquery 更改选项值? 的相关文章