简体   繁体   English

Javascript 仅页面上的第一个(不是全部)实例

[英]Javascript only first one (not all) instances on page

I'm trying to hide a list item, based on the text within the list <p> .我正在尝试根据列表<p>中的文本隐藏列表项。 I have it almost right.我几乎是对的。 However, my current version doesn't find every instance on a page.但是,我当前的版本没有找到页面上的每个实例。 It finds, and hides, the last instance, but not the others.它找到并隐藏最后一个实例,而不是其他实例。 There can be 3-4 of these on a page I would like to hide.我想隐藏的页面上可以有 3-4 个。

Help appreciated.帮助表示赞赏。

 // select relevant elements var elements = $('p'); // go through the elements and find the one with the value elements.each(function(index, domElement) { var $element = $(domElement); // does the element have the text we're looking for? if ($element.text() === "Happy New Year (Southern)") { $element.parent().hide(); // hide the element with jQuery return false; // jump out of the each } });

What about using filter first, and then only hiding the elements after that?那么先使用过滤器,然后只隐藏元素呢?

 // select relevant elements var elements = $('p'); // go through the elements and find the one with the value elements.filter(function(index) { return $(this).text() === "Happy New Year (Southern)"; }).eq(0).parent().hide();
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li> <p>Happy New Year (Northern)</p> </li> <li> <p>Happy New Year (Eastern)</p> </li> <li> <p>Happy New Year (Southern)</p> </li> <li> <p>Happy New Year (Southern)</p> </li> <li> <p>Happy New Year (Southern)</p> </li> <li> <p>Happy New Year (Western)</p> </li> </ul>

Using .eq(0) we select only the "first" matched item, and then hide the parent.使用.eq(0)我们 select 仅“第一个”匹配项,然后隐藏父项。

To hide all of them, we just omit the .eq(0) .要隐藏所有这些,我们只需省略.eq(0)

Maybe this will help:也许这会有所帮助:

var elements   = document.getElementsByTagName("p");
var searchText = "Happy New Year (Southern)";

for (var i = 0; i < elements.length; i++) {
    if (elements.textContent == searchText) {
        elements[i].parent().hide()
    }
}

As commented removing the return false;正如评论删除return false; has solved this.解决了这个问题。 Thanks!谢谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM