JQuery如何从下拉选项中精确选择我需要的文本?

时间:2011-10-24 07:03:29

标签: jquery

:contains这里不是为我做的。它太粗糙了。我似乎无法找到正确的方法来获得它。

(.js如下)

$(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"/>

http://jsfiddle.net/KGabbert/mCDer/3/

4 个答案:

答案 0 :(得分:9)

它返回cabd选项,因为它包含“ab”,而这正是:contains所用的内容。如果您想要返回完全匹配的option的值,可以使用filter

var optionThatMatchesCookie = $("#" + select + " option").filter(function() {
     return $(this).val() === cookieVal;  
}).val();

这是working example

顺便说一句,请注意typeof是一个运算符,而不是一个方法,所以你不应该把操作数放在括号中:

typeof optionThatMatchesCookie

另请注意,您可以将代码显着缩短为:

$(function() {
    $('#my_button').click(function() {
        var cookieVal = "ab",
            select = "combo0";
        $("#" + select).val(cookieVal); 
    });
});

如果cookieVal与其中一个option元素的值不匹配,则该值不会更改。请参阅另一个working example here

答案 1 :(得分:0)

使用此代码返回cookieVal的匹配项:

    var optionThatMatchesCookie = $("#" + select + " value=['" + cookieVal +"']").val()

答案 2 :(得分:0)

通常最好不要动态构建选择器:

$(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);
        }
    });
});

答案 3 :(得分:0)

刚刚发现:

var optionThatMatchesCookie = $('#' + select).children('option[text="' + cookie + '"]').val();

哪个更好,这个或.filter()回答?