javascript - 如何根据子元素的文本值隐藏父元素

标签 javascript jquery

我想要的是能够在 DOM 中搜索某个字符串。如果文本位于页面上,则隐藏某些元素并显示其他元素。问题是 id 是在 PHP foreach 语句中动态给出的。

我尝试搜索特定于文本的 .exists() 函数。到目前为止我已经尝试过:

jQuery(document).ready(function($) {
    var string1 = 'string1',
        string2 = 'string2';

    if ($('li').children().text() === string1) {
        if ($('li').children().text() === string2) {
            $(this).parent().show();
        } else {
            $(this).parent().hide();
        }
    } else {
        if ($('li').children().text() === string2) {
            $(this).parent().hide();
        } else {
            $(this).parent().show();
        }
    }
});

所以我正在寻找:

1) 搜索页面 string1。

2) 如果页面上存在 string1,则显示包含 string2 的子元素的父元素并隐藏任何其他字符串。

3) 如果不存在则隐藏 string1 和 string2。

但这不起作用。我并不是最擅长 Jquery/JS,总的来说我还是个初学者。

最佳答案

要查看一个字符串是否包含另一个(子)字符串,您可以使用 indexOf 。 并检查它是否不为-1。

使用 each() 您可以循环遍历所有 li 元素。考虑到你的 jsFiddle (在评论中提供),我得到了这个结果:http://jsfiddle.net/ub8c6smh/5/

jQuery(document).ready(function($) {
    var string1 = 'string1',
        string2 = 'string2';
    var string1exists= $('li').text().indexOf( string1)!==-1;
    console.log(string1exists);

    $('li').each(function () {
         if ($(this).text().indexOf( string2)!==-1 && string1exists==true) {
             // this child contains string 2
            $('li').hide(); //hide all others
            $(this).show();                    
        }
        if ($(this).text().indexOf( string2)!==-1 && string1exists==false) {
             // this child contains string 2
            $(this).hide();                    
        }
        if ($(this).text().indexOf( string1)!==-1 && string1exists==false) {
             // this child contains string 1
            $(this).hide();                    
        }
    });

});

关于javascript - 如何根据子元素的文本值隐藏父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33876673/

相关文章:

c# - 如何用javascript将文本框的值相乘

javascript - 使用 vue.js 根据最多投票排列数据(评论)

javascript - 如何使用 angularjs 添加 google webkit

javascript - 如何在未标记复选框时始终显示 div 元素

javascript - 在当前点击的TD中打开div

java - GAE : Slow delayed requests

javascript - 预填充文本字段的脚本

javascript - 为什么会:after be drawed strangely?

jquery .get 数据操作

javascript - 更改类 IF 下拉列表和 H2 内容与 Animate.css 匹配某些条件