[英]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.