簡體   English   中英

如何根據孩子的文本值隱藏父元素

[英]How to hide parent element based on child's text value

我想要的是能夠在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();                    
        }
    });

});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM