javascript - 根据其中子元素的文本值获取单行元素?

标签 javascript jquery

如何根据其中子项的文本值获取单行元素?例如,如果我有以下内容:

<div class="row">
    <div class="a">AA</div>
    <div class="b">B</div>
    <div class="c">C</div>
</div>
<div class="row">
    <div class="a">AA</div>
    <div class="b">BB</div>
    <div class="c">CC</div>
</div>
<div class="row">
    <div class="a">AAA</div>
    <div class="b">BB</div>
    <div class="c">CC</div>
</div>

如何根据具有带 AA 的子类“a”div 和带 BB 的“b”类 div 以及带 CC 的“c”类 div 的行获取第二行?

var elem = $('.row'); // How can I get a particular row based on the text values of the children elements in it?

最佳答案

你应该使用 .filter()连同.has()

Reduce the set of matched elements to those that match the selector or pass the function's test.

var elem = $('.row').filter(function(){
    var _this = $(this);
    var hasA = _this.has('div.a'); 
    var hasB = _this.has('div.b');
    var hasC = _this.has('div.c');

    if(hasA && hasB && hasC){
        return _this.find('div.a').text().trim() == 'AA'
            && _this.find('div.b').text().trim() == 'BB'
            && _this.find('div.c').text().trim() == 'CC'
    }

    return false;   
}); 

根据要求

function getElements(valueForA, valueForB, valueForC){
    return $('.row').filter(function(){
        var _this = $(this);
        var hasA = _this.has('div.a'); 
        var hasB = _this.has('div.b');
        var hasC = _this.has('div.c');

        if(hasA && hasB && hasC){
            return _this.find('div.a').text().trim() == valueForA
                && _this.find('div.b').text().trim() == valueForB
                && _this.find('div.c').text().trim() == valueForC
        }

        return false;   
    }); 
}

关于javascript - 根据其中子元素的文本值获取单行元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34895757/

相关文章:

javascript - 在 sweet alert 上单击确定按钮后如何重定向页面?

javascript - 如何使用 Firefox/Firebug 或其他浏览器查看 jquery data()

javascript - servlet - 为什么 XMLHttpRequest 响应文本总是空白?

jquery - 在 JQGrid 中显示 Twitter Bootstrap 下拉菜单

javascript - 如何用公司图标替换页面加载器

javascript - 在 AJAX 调用中发送 DIV 元素的 ID

jquery - 将 Jquery onclick 事件添加到某个类中的所有链接

javascript - "$"符号在 jQuery 或 JavaScript 中意味着什么?

Javascript:如果文本输入有任何值

javascript - jquery 对象没有方法 live