JQuery如何从下拉选项中准确选择所需的文本?
例如:我在这里不是为我做的。太粗糙了。我似乎无法找到正确的方法来获得它 下面是一把小提琴JQuery如何从下拉选项中准确选择所需的文本?,jquery,Jquery,例如:我在这里不是为我做的。太粗糙了。我似乎无法找到正确的方法来获得它 下面是一把小提琴 $(function() { $('#my_button').click(function() { var cookieVal = "ab"; //This is what I want to find var select = "combo0"; var optionThatMatchesCookie = $("#" + select + " op
$(function() {
$('#my_button').click(function() {
var cookieVal = "ab"; //This is what I want to find
var select = "combo0";
var optionThatMatchesCookie = $("#" + select + " option:contains('" + cookieVal + "')").val();
alert(optionThatMatchesCookie); //returns the wrong entry! (returns 'cabd' not 'ab')
if (typeof(optionThatMatchesCookie) != "undefined") {
//now put that in the combobox
$('#' + select).val(optionThatMatchesCookie);
}
});
});
<select class="inputfield" id="combo0" name="jobType">
<option selected="selected">-select-</option>
<option id="1">sssssssssss</option>
<option id="18">fffffffffff</option>
<option id="47">cabd</option>
<option id="3">LPN/LVN</option>
<option id="22">bbbbb</option>
<option id="17">hhhhhhhhhh</option>
<option id="15">aaaaaaa</option>
<option id="16">zzzzzzzzzzzzzzz</option>
<option id="5">ab</option>
<option id="44">YYYYYYYYY</option>
<option id="19">XXXXXX</option>
</select>
<input type="button" id="my_button" value="test me"/>
它返回cabd选项,因为它包含ab,而这正是:contains的用途。如果要返回完全匹配的选项值,可以使用:
这是一个例子
另请注意,这是一个运算符,而不是一个方法,因此不应将操作数放在括号中:
typeof optionThatMatchesCookie
还请注意,您可以将代码显著缩短为:
$(function() {
$('#my_button').click(function() {
var cookieVal = "ab",
select = "combo0";
$("#" + select).val(cookieVal);
});
});
如果cookieVal与其中一个选项元素的值不匹配,则该值不会更改。请参阅另一个。使用此代码返回cookieVal的匹配项:
var optionThatMatchesCookie = $("#" + select + " value=['" + cookieVal +"']").val()
通常,最好不要动态构建选择器:
$(function() {
$('#my_button').click(function() {
var cookieVal = "ab"; //This is what I want to find
var select = $("#combo0"); //Select the combo here
var optionThatMatchesCookie = select.find("option").filter(function() {
return $(this).text() === cookieVal;
}).text();
alert(optionThatMatchesCookie); //returns the wrong entry! (returns 'cabd' not 'ab')
if (typeof(optionThatMatchesCookie) != "undefined") {
//now put that in the combobox
select.val(optionThatMatchesCookie);
}
});
});
刚找到这个:
var optionThatMatchesCookie = $('#' + select).children('option[text="' + cookie + '"]').val();
哪个更好,这个还是.filter答案?看起来你是指.val,不是。text@Eric-你说的是哪一部分?我的意思是.text不是.val,在第一个代码段的末尾,现在已更改,但不确定我的意思是.val而不是.text。@Eric-抱歉,请重新阅读我的答案,并了解您的意思。我弄糊涂了。谢谢您可以通过:$+select.valcookieVal;我现在明白了,我一直在认真思考这个问题。@KevinDeus——总是这样:在写下剩下的答案后,我花了一段时间才意识到事情就是这么简单!很高兴我能帮忙。
var optionThatMatchesCookie = $('#' + select).children('option[text="' + cookie + '"]').val();