jQuery使用:contains()来搜索选项的值:selected

时间:2011-08-08 05:33:59

标签: jquery

我正在尝试检查$('select option:selected')。val();包含某些单词,如果是,则重定向到某个页面。

这是我的HTML:

<select name="people_view" id="people_view">
    <optgroup label="People Categories">
        <option value="category_1">Members</option>
        <option value="category_2">Connections</option>     
    </optgroup>
    <optgroup label="Groups">
        <option value="group_1">Group 1</option>
        <option value="group_2">Group 2</option>
        <option value="group_3">Group 3</option>
    </optgroup>
    <optgroup label="Custom Views">
        <option value="view_1">Test People View</option>
    </optgroup>
</select>

这是我的JS:

    if ($('#people_view option:selected:contains("category_")')) {

        categoy_id = $(this).val().replace('category_', '');
        window.location.href = admin_url + 'people/?category=' + categoy_id;

    } else if ($('#people_view option:selected:contains("group_")')) {

        group_id = $(this).val().replace('group_', '');
        window.location.href = admin_url + 'people/?group=' + group_id;

    } else if ($('#people_view option:selected:contains("view_")')) {

        view_id = $(this).val().replace('view_', '');
        window.location.href = admin_url + 'people/?view=' + view_id;

    }

是否不能同时使用两个选择器(例如:selected:contains())。或者我只是做错了什么?

感谢您的帮助!

2 个答案:

答案 0 :(得分:2)

$('#people_view').change(function() {
    var val = $(':selected', this).val();
    var arr = val.split('_');
    console.log(admin_url + 'people/?' + arr[0] + '=' + arr[1]); // this for your visual of the url. delete this line
    //window.location.href = admin_url + 'people/?'+ arr[0] +'=' + arr[1]; // uncomment this line
});

答案 1 :(得分:1)

改变这个:

if ($('#people_view option:selected:contains("category_")')) {

要:

if ($('#people_view option:selected:contains("category_")').length) {

等等。

你也可以这样做

$('option:selected').filter(':contains(blah), :contains(blah2)')

所有这一切都将是:

if ($('#people_view option:selected').filter(':contains(category_), :contains(group_), :contains(view_)').length)
//...