2010-10-28 43 views
28

好吧我有列表項目,有些有跨度,有些沒有。
在我的活動中,我想添加跨度,當他們還沒有。jquery過濾有+不是

has()工作正常,但not()增加跨度?

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>'); 
    })  
}) 
+0

參見http://stackoverflow.com/questions/2624832/jquery-selector-for-div-which- does not-contain-img – goodeye 2015-02-15 18:15:54

回答

72

您可以使用:not:has選擇的組合這樣

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

這裏是一個demohttp://www.jsfiddle.net/xU6fV/

+0

@FFISH ...這是一個更清潔的解決方案 – 2010-10-28 17:36:15

+2

yup +1那裏:) – Sarfraz 2010-10-28 17:41:07

+0

不錯的組合,並沒有,最後我選擇Sarfraz選項,因爲我有每個循環中的另一個過濾器,謝謝! – FFish 2010-10-28 18:24:02

2
$("a.add-span").click(function() { 
    $("li").each(function(index) { 
     if ($(this).children('span').length === 0){ 
     $(this).append('<span class="spn">new span<\/span>'); 
     } 
    })  
}) 

隨着children()法,length屬性用於檢查是否不span已經存在,如果沒有,一個被添加/附加。

更多信息:

+0

你不是指'if($(this).children('span')...'?但是否則,+1。甚至沒有想到這種方法=) – 2010-10-28 17:21:32

+0

@Jeff Rupert:的確,這是'孩子',我沒有專注於他的選擇。謝謝 – Sarfraz 2010-10-28 17:23:53

+0

@Sarfraz ... wouldint它會更容易,只是在選擇器中指定每個函數... IE $(「li:not(:has(span))」)。)each(...) – 2010-10-28 17:30:49

1

接受的答案效果很好,如果你不希望過濾掉僅做有span S作爲直接孩子的那些元素。

由於:has().has()遍佈所有的後代,而不僅僅是孩子。

在這種情況下,你必須使用一個功能

$("li").not(function() { 
    // returns true for those elements with at least one span as child element 
    return $(this).children('span').length > 0 
}).each(function() { /* ... */ }) 
0

試試這個,

$("a.add-span").click(function() { 
    $("li:not(:has(span))").each(function(index) { 
     $(this).append($("<span class='spn'>").html("Newly Added Span")); 
    }); 
}); 
0

這是谷歌第一個鏈接搜索「的jquery不有」的時候。我需要解決的具體情況與此有所不同。我不得不not項目具有特定的DOM元素,而不是簡單地基於標籤。這意味着我無法使用上面每個解決方案使用的選擇器。

jQuery的has()但確實接受DOM元素!所以我創建了一個jQuery插件來組合這兩個內置函數。

我想在這裏分享它,因爲希望它能幫助別人也適應我的情況。它也回答了原來的問題。

插件:

(function ($) { 
    $.fn.extend({ 
     not_has: function (param) { 
      return this.not(this.has(param)); 
     } 
    }); 
}(jQuery)); 

實現:

$("a.add-span").click(function() { 
    $("li").not_has("span") 
    .append('<span class="spn">new span<\/span>'); 

    // Prevent the page from navigating away 
    return false; 
}); 

https://jsfiddle.net/brjkg10n/1/


我最初打算找一個jQuery功能,將工作就像addBack()但使用not代替。如果您需要如此複雜的內容,請隨時使用以下插件。

(function ($) { 
    $.fn.extend({ 
     notBack: function() { 
      return this.prevObject.not(this); 
     } 
    }); 
}(jQuery)); 

這樣,答案會是:

$("li").has("span").notBack() 
.append('<span class="spn">new span<\/span>'); 

https://jsfiddle.net/2g08gjj8/1/