jQuery选择器格式

问题描述 投票:0回答:1

我有一个问题,我已经处理了一段时间了。

场景:我有一个网页,有几个下拉列表(html选择)。我想使用每个语句(在jQuery中)遍历所有下拉列表,然后搜索每个下拉列表中的特定文本元素的选项。所以我有这个:

$.each(selects, function(ind, elem){ 
    var $this = $(elem);
    $($this + ' option').filter(function() { return $(this).text() === 'some text';});
});

我收到一条错误消息:Syntax error, unrecognized expression: [object Object] option

有谁知道如何组合像$this和选择器文本这样的对象来获得我想要的结果?

任何帮助都会很棒。

谢谢,T

jquery css-selectors each
1个回答
0
投票

所以你需要在Document ready事件上编写JS代码。

如果搜索到的文本匹配,以下代码将返回该选项。我已经添加了一个Selected属性来理解 -

$( document ).ready(function() {
    var selects = $("select");
    $(selects).each(function(index, elem){
        var searchText = "c";
        if($(elem).find('option[value="'+searchText+'"]').length > 0){
            var searchResultElem = $(elem).find('option[value="'+searchText+'"]');
            searchResultElem.attr('selected','selected');
            console.log(searchResultElem);
        }
    });
});
© www.soinside.com 2019 - 2024. All rights reserved.