如何使用其数据属性查找和设置 HTML-Select 选项元素?
How to find and set an HTML-Select option element using its data attribute?
我有以下 HTML:
<select name="1028071" class="LC" id="1028071" style="width: 100%;">
<option selected="selected" value="-1">[Please select a value]</option>
<option value="10604534" data-uid="154b2706-505e-401c-a066-a37a1889e3be">[Other]</option>
<option value="10604535" data-uid="25070b3b-8215-440b-b3cf-c6cf52f01efc">Reason 1</option>
<option value="10604536" data-uid="fd3394ea-a7e8-45e8-8385-71dee98238ff">Reason 2</option>
</select>
我正在尝试 select [Other]
。 value
和文本都是变量。跨环境的唯一固定值是 data-uid
.
我尝试了以下方法,但没有用:
var other = $(formalRequestReasonFieldId).find("option").filter(function() {
return $(this).data('uid') == '154b2706-505e-401c-a066-a37a1889e3be';
});
alert(other.text()); // returns blank text
other.attr('selected', true); // does not work, no errors
如果 formalRequestReasonFieldId 是 Select 标签 ID :
var other = $('#'+formalRequestReasonFieldId).find('option[data-uid="154b2706-505e-401c-a066-a37a1889e3be"]');
//Other Text
var text = other.text();
//Select It
other.prop("selected", true);
JSFiddle:https://jsfiddle.net/6opqnxhy/
我有以下 HTML:
<select name="1028071" class="LC" id="1028071" style="width: 100%;">
<option selected="selected" value="-1">[Please select a value]</option>
<option value="10604534" data-uid="154b2706-505e-401c-a066-a37a1889e3be">[Other]</option>
<option value="10604535" data-uid="25070b3b-8215-440b-b3cf-c6cf52f01efc">Reason 1</option>
<option value="10604536" data-uid="fd3394ea-a7e8-45e8-8385-71dee98238ff">Reason 2</option>
</select>
我正在尝试 select [Other]
。 value
和文本都是变量。跨环境的唯一固定值是 data-uid
.
我尝试了以下方法,但没有用:
var other = $(formalRequestReasonFieldId).find("option").filter(function() {
return $(this).data('uid') == '154b2706-505e-401c-a066-a37a1889e3be';
});
alert(other.text()); // returns blank text
other.attr('selected', true); // does not work, no errors
如果 formalRequestReasonFieldId 是 Select 标签 ID :
var other = $('#'+formalRequestReasonFieldId).find('option[data-uid="154b2706-505e-401c-a066-a37a1889e3be"]');
//Other Text
var text = other.text();
//Select It
other.prop("selected", true);
JSFiddle:https://jsfiddle.net/6opqnxhy/