gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 06:40:23 28 4
gpt4 key购买 nike

我想要的是能够在 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/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com