【问题标题】:How to hide parent element based on child's text value如何根据子元素的文本值隐藏父元素
【发布时间】:2015-11-24 02:09:58
【问题描述】:

我想要的是能够在 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) 搜索字符串 1 的页面。

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

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

但这不起作用。我在 Jquery/JS 方面不是最优秀的,总的来说我是它的初学者。..

【问题讨论】:

  • 请提供您的 HTML 示例。不过,您的第一个 if 语句似乎是多余的,因为您在两种情况下都有相同的逻辑。
  • html 是使用 foreach 循环动态生成的 - 我可以添加它,但您会看到的唯一内容是 $this->getTitle() 等。
  • 请描述您想要实现的目标,因为您的代码条件不正确。
  • 查看修改后的问题
  • 你所说的搜索字符串1的页面是什么意思?在所有文档 DOM 中搜索?

标签: javascript jquery


【解决方案1】:

要查看一个字符串是否包含另一个(子)字符串,您可以使用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();                    
        }
    });

});

【讨论】:

  • 不幸的是,它不起作用:(如果需要,请参阅修改后的问题以获取更多信息
  • 您需要遍历孩子。让我更新我的答案
  • 赞成建议 .each() 不过,我认为这可能为我指明了正确的方向。
  • @TT120 这就是你想要的吗? jsfiddle.net/ub8c6smh/4 (PS: 不要忘记在 jsfiddle 中包含 jQuery)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多