Javascript jQuery:not:contains隐藏与数组值不匹配的元素
我只需要显示myArray中包含值的Javascript jQuery:not:contains隐藏与数组值不匹配的元素,javascript,jquery,Javascript,Jquery,我只需要显示myArray中包含值的元素。如果我在myArray中只有一个值,但对多个值无效,那么它就可以工作 let myArray = ["10/07/2020", "11/07/2020", "12/07/2020", "13/07/2020", "14/07/2020"] // not working let myArray = ["10/07/2020"]
元素。如果我在myArray中只有一个值,但对多个值无效,那么它就可以工作
let myArray = ["10/07/2020", "11/07/2020", "12/07/2020", "13/07/2020", "14/07/2020"] // not working
let myArray = ["10/07/2020"] // works
<ul class = "quotes">
<li class = "quote"> blablabla 11/07/2020 </li>
<li class = "quote"> blablabla 12/07/2020</li>
<li class = "quote"> blablabla 12/07/2020</li>
<li class = "quote"> blablabla 18/07/2020</li>
<li class = "quote"> blablabla 20/07/2020</li>
<li class = "quote"> blablabla 22/07/2020</li>
</ul>
$(myArray ).each(function () {
$(".quote:not(:contains("+ this +))").hide();
});
让myArray=[“10/07/2020”、“11/07/2020”、“12/07/2020”、“13/07/2020”、“14/07/2020”]//不工作
让myArray=[“10/07/2020”]//工作
- bla 2020年7月11日
- 2020年7月12日
- 2020年7月12日
- bla 2020年7月18日
- 2020年7月20日
- 2020年7月22日
$(myArray)。每个(函数(){
$(“.quote:not(:contains(“+this+”)).hide();
});
你知道如何让它工作吗?试试这个:
$(“.quote:not(:contains(“+this+”)))”))。hide();
更新:
$.each(myArray, function(i, v) {
$(".quote:not(:contains('" + v + "'))").hide();
});
您可以使用
.some
循环所有引号元素,并检查其文本是否包含数组中的任何元素
$('.quote').each(function(){
let text = $(this).text();
if(!myArray.some(x => text.includes(x))){
$(this).hide();
}
});
如果您能够应用包装相关文本(在本例中为日期),那么您呈现的数据将更容易访问,也更容易查找和使用 因此,我选择使用
元素来包装日期,并产生了以下简单的JavaScript方法:
// the array of dates:
let myArray = ["10/07/2020", "11/07/2020", "12/07/2020", "13/07/2020", "14/07/2020"];
// here we find all the <time> elements, using
// document.querySelectorAll(); and then chain
// the resulting NodeList with
// NodeList.prototype.forEach() in order to iterate
// over each of the found Nodes:
document.querySelectorAll('time').forEach(
// here we use an Arrow function expression, where
// 'd' is a reference to the current node of the
// NodeList we're iterating over, and is passed to
// the function:
(d) => {
// we navigate from the <time> Node ('d') to its
// parentNode the <li>:
d.parentNode
// here we access the <li> element's classList
// property (a list of class-names that the
// element has):
.classList
// and we toggle the 'hidden' class-name, based on
// the result of the 'switch' the test that follows,
// here we use Array.prototype.includes() to find
// if the Array includes an entry equal to the
// textContent of the <time> element; if so the
// switch evaluates to (Boolean) true and the
// class-name is applied, if the expression results
// in a false, or falsey, value then the class is
// removed (no error is generated if the class is
// already present or absent):
.toggle('hidden', myArray.includes(d.textContent))
});
。隐藏{
不透明度:0.4;
}
- bla 2020年7月11日
- 2020年7月12日
- bla 2020年7月11日
- bla 2020年7月18日
- 2020年7月20日
- 2020年7月22日