简体   繁体   English

如何在选择选项字段中选择特定的自定义属性?

[英]How select specific custom attribute in an select option field?

I'm fixing a horrendous bug in an old web application. 我正在修复旧的Web应用程序中的一个严重错误。 For some datasets, the values in an option/select list are unfortunately not unique. 对于某些数据集,不幸的是,选项/选择列表中的值不是唯一的。 But luckily, the custom attribute test is unique. 但幸运的是,自定义属性test是唯一的。

So I have the following HTML structure: 因此,我具有以下HTML结构:

<select id="dropdown">
    <option value="1" test="A">fooA</option>
    <option value="2" test="B">fooB</option>
    <option value="2" test="C">fooC</option>
    <option value="2" test="D">fooD</option>
    <option value="2" test="E">fooE</option>
</select>

So I wonder how could set C from the custom attribute test with the help of Jquery or vanilla JS in the select/dropdown field? 因此,我想知道如何在选择/下拉字段中借助Jquery或Vanilla JS在自定义属性test设置C The .attr() property only changes the properties of the custom attribute test , which I not want. .attr()属性仅更改自定义属性test的属性,而我不需要。 I want to set fooC in the select field. 我想在选择字段中设置fooC

JSFiddle link to try: http://jsfiddle.net/rnnfk/120/ 尝试使用JSFiddle链接: http : //jsfiddle.net/rnnfk/120/

First you need to select the attribute with the help of css attribute selector then add selected attribute using attr() . 首先,您需要借助css属性选择器来选择属性,然后使用attr()添加selected属性。

Try this technique. 试试这种技术。 Demo 演示版

$('#dropdown option[test=C]').attr( "selected","selected");

You can use attribute selector to get the option with attribute test with specific value. 您可以使用属性选择器来获取具有特定值的属性测试的选项。

Live Demo 现场演示

$('#dropdown option[test=C]').prop('selected', true);

Just add following code in jquery :- 只需在jquery中添加以下代码:

$("#dropdown [test='C']").attr("selected", "selected");

It may help you. 它可能会帮助您。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM