jQuery过滤有+没有 [英] jquery filtering has + not

查看:104
本文介绍了jQuery过滤有+没有的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我有列表项,有些有跨度,有些没有.
在我的活动中,我想在他们还没有跨度时添加跨度.

Okay I have list items, some have a span, some not.
On my event I want to add the span when they don't have any yet.

has()可以正常工作,但是not()将跨度都添加到两者中?

has() works fine, but not() adds the span to both??

HTML:

<ul>
    <li>
        <p>item</p>
        <span class="spn">empty span</span>
    </li>
    <li>
        <p>item 2</p>
    </li>
<ul>
<hr>
<a class="add-span"href="#">check</a>

JS:

$("a.add-span").click(function() {
    $("li").each(function(index) {
        // $(this).has("span").find("span").append(" - appended");
        $(this).not("span").append('<span class="spn">new span<\/span>');
    })    
})

推荐答案

您可以结合使用 :not :具有选择器

You can use a combination of the :not and :has selectors like this

$("a.add-span").click(function() {
    $("li:not(:has(span))").each(function(index) {
        $(this).append('<span class="spn">new span<\/span>');
    });
});

这是演示 查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆