jquery 删除列表项 where .text() = 'blabla'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3713664/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 15:57:52  来源:igfitidea点击:

jquery remove list item where .text() = 'blabla'

jquery

提问by Hailwood

I have the following structure

我有以下结构

<ul>
 <li><a ...>something</a></li>
 ...
 <li><a ...>blabla</a></li>
<ul>

I need to remove the lielement where the text of the anchor is blabla.

我需要删除li锚文本为blabla的元素。

How would i go about selecting this element? $(--what selector here--)

我将如何去选择这个元素? $(--what selector here--)

or do I need to loop over each liand compare its .text()value to 'blabla'?

还是我需要遍历每个li并将其.text()值与“blabla”进行比较?

回答by Nick Craver

If you want a contains(substring match) then :contains()works:

如果你想要一个包含(子字符串匹配)然后:contains()工作:

$('li:contains("blabla")').remove();

If you want an exactmatch, e.g. not matching "blablabla", you can use .filter():

如果您想要完全匹配,例如不匹配“blablabla”,您可以使用.filter()

$('li').filter(function() { return $.text([this]) === 'blabla'; }).remove();

回答by alex

$('li > a:contains("blabla")').remove();

Have a look at the :contains selector.

看看:contains 选择器

I've just noticedthat :containsdoes partial matching. You may need to do...

只注意到:contains确实部分匹配。你可能需要做...

$('li > a:contains("blabla")').each(function() {
     if ($(this).text() === 'blabla') {
         $(this).parent().remove();
     }
});

You could also make the selector less strict if doing it that way.

如果这样做,您还可以使选择器不那么严格。

... or you could do it much neater like Nick Craver.

......或者你可以像 Nick Craver 那样做得更整洁

回答by Chris Laplante

If you want to avoid removing lis containing blablaunless blablais further nested, use this:

如果您想避免删除li包含blabla除非blabla进一步嵌套的s ,请使用以下命令:

$("ul li > a:contains('blabla')").parent().remove();

$("ul li > a:contains('blabla')").parent().remove();

Otherwise, the first lifrom this HTML will be removed even though "blabla" is not where you might be targeting it:

否则,li即使“blabla”不是您可能将其定位的位置,该 HTML 中的第一个也将被删除:

<ul>
    <li>
        <div>
            Some nested content here:
            <span>
                Blablabla
            </span>
        </div>
    </li>
    <li>Some text</li>
</ul>