我只需要显示在myArray中包含值的<li>
元素。如果我在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();
});
有任何想法如何使其正常工作吗?
答案 0 :(得分:1)
如果您能够套用相关文本(在这种情况下为日期),则可以更轻松地访问要显示的数据,并且更易于查找和使用。
因此,我选择使用<time>
元素来包装日期,并产生了以下纯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))
});
let myArray = ["10/07/2020", "11/07/2020", "12/07/2020", "13/07/2020", "14/07/2020"];
document.querySelectorAll('time').forEach(
(d) => {
d.parentNode.classList.toggle('hidden', myArray.includes(d.textContent))
});
.hidden {
opacity: 0.4;
}
<ul class="quotes">
<li class="quote"> blablabla <time>11/07/2020</time></li>
<li class="quote"> blablabla <time>12/07/2020</time></li>
<li class="quote"> blablabla <time>11/07/2020</time></li>
<li class="quote"> blablabla <time>18/07/2020</time></li>
<li class="quote"> blablabla <time>20/07/2020</time></li>
<li class="quote"> blablabla <time>22/07/2020</time></li>
</ul>
参考:
答案 1 :(得分:0)
尝试一下:
$(".quote:not(:contains('" + this + "'))").hide();
更新:
$.each(myArray, function(i, v) {
$(".quote:not(:contains('" + v + "'))").hide();
});
答案 2 :(得分:0)
您可以使用.some
遍历所有引号元素,并检查其文本是否包含数组中的任何元素。
$('.quote').each(function(){
let text = $(this).text();
if(!myArray.some(x => text.includes(x))){
$(this).hide();
}
});