2013-04-18 62 views
5

我創建了一個小型的jsfiddle: http://jsfiddle.net/duRXc/jQuery的刪除(選擇)似乎不工作

<div data-role="wrapper"> 
    <span class="to-be-removed" data-role="to-be-removed"> 
     text to be removed 
    </span> 
</div> 
<button id="remove1">Remove by jQuery object</button><br> 
<button id="remove2">Remove by selector</button><br> 
<button id="remove3">Remove by selector(class)</button> 

var $wrapper = $('[data-role="wrapper"]'); 

$('#remove1').on('click', function() { 
    $wrapper.find('[data-role="to-be-removed"]').remove(); 
}); 

// this should work: http://api.jquery.com/remove/ 
$('#remove2').on('click', function() { 
    $wrapper.remove('[data-role="to-be-removed"]'); 
}); 

// this should work: http://api.jquery.com/remove/ 
$('#remove3').on('click', function() { 
    $wrapper.remove('.to-be-removed'); 
}); 

我遇到的問題是,卸下襬臂(選擇)的過載是行不通的。我認爲這與我的數據角色選擇器有關,但通過類選擇器移除不起作用。

我做錯了什麼?或者,這是jQuery的錯誤或可能的文檔是錯誤的:

我們還可以包括一個選擇器作爲可選參數

http://api.jquery.com/remove/

回答

5

$wrapper.find('span').remove('[data-role="to-be-removed"]')

是一樣的

$wrapper.find('span').filter('[data-role="to-be-removed"]').remove()

var $wrapper = $('[data-role="wrapper"]'); 

$('#remove1').on('click', function() { 
    $wrapper.find('[data-role="to-be-removed"]').remove(); 
}); 

// this should work: http://api.jquery.com/remove/ 
$('#remove2').on('click', function() { 
    $wrapper.find('[data-role="to-be-removed"]').remove('[data-role="to-be-removed"]'); 
}); 

// this should work: http://api.jquery.com/remove/ 
$('#remove3').on('click', function() { 
    $wrapper.find('[data-role="to-be-removed"]').remove('.to-be-removed'); 
}); 

http://jsfiddle.net/duRXc/3/

+1

感謝一大堆! – Jaap

3

要刪除一個選擇器匹配的子元素,你可以使用:

$('[data-role="to-be-removed"]', $wrapper).remove(); 

The remove(selector)方法是進一步過濾現有的選擇。例如...

<ul id="test"> 
    <li>One</li> 
    <li class="example">Two</li> 
    <li>Three</li> 
</ul> 

如果我選擇所有列表項,然後我就可以刪除任何與我的過濾器,這些列表項:

$('#test li').remove('.example'); 

有一個running example of this on JSFiddle

0

選擇器僅支持包裝對象中的元素。 所以,如果你使用一個div來代替span,並選擇所有的div作爲wrapper,它就可以工作。

例如http://jsfiddle.net/hsLLr/

<div data-role="wrapper"> 
    <div class="to-be-removed" data-role="to-be-removed"> 
     text to be removed 
    </div> 
</div> 
<button id="remove1">Remove by jQuery object</button><br> 
<button id="remove2">Remove by selector</button><br> 
<button id="remove3">Remove by selector(class)</button> 

var $wrapper = $('div'); 

$('#remove1').on('click', function() { 
    $wrapper.find('[data-role="to-be-removed"]').remove(); 
}); 

// this should work: http://api.jquery.com/remove/ 
$('#remove2').on('click', function() { 
    $wrapper.remove('[data-role="to-be-removed"]'); 
}); 

// this should work: http://api.jquery.com/remove/ 
$('#remove3').on('click', function() { 
    $wrapper.remove('.to-be-removed'); 
}); 
+0

你錯過了這一點,$包裝需要具體,現在你只是選擇*所有* divs和篩選他們... – Jaap