2011-10-06 86 views
0

我有一些這樣的。如何構建jQuery刪除

<script src="http://code.jquery.com/jquery-latest.js"></script> 
<table> 
<tr title="test" id="ex1"> 
    <td><div class="move">Hello</div></td> 
    <td>&nbsp;</td> 
    <td>&nbsp;</td> 
</tr> 
<tr id="ex2"> 
    <td><div class="move">Hello</div></td> 
    <td>&nbsp;</td> 
    <td>&nbsp;</td> 
</tr>  
</table> 

<button>Move</button> 
<script> 
$("button").click(function() { 
    $(".move").remove(); 
    }); 
</script> 

如果我按下按鈕,兩個div都會移動。但是我只需要移動一個,根據它放置的標識。

我只有錯誤的想法:

$(".move").parent.parent.attr('id', 'ex2').remove(); 

太謝謝你了!

回答

1

這將是

$("#ex2 .move").remove(); 

簡單吧?請記住,jQuery選擇器與CSS選擇器相同。

+2

我覺得這其實是最好的答案,如果只有EX2是一個類,而不是一個ID?它應該是$(「#ex2 .move」)。remove(); – adeneo

+1

它應該不是'$('#ex2 .move「)。remove()'作爲'ex2'是一個ID? –

+0

是的,我的不好,是固定的。 –

1

你可以簡化這個。

$('.move').parents('tr').remove(); 

這將找到最近的父母也是<tr>並將刪除它。

...等等。所以你想單擊一個按鈕,然後讓它只刪除具有該特定ID的一個div?

在這種情況下,只需使用

$('.move').parents('#ex2').remove(); 
0

試試這個: - jsFiffle

$(".move", "#ex2").remove(); 

這樣做是選擇與CSS類的move id爲ex2元素的所有子元素(上下文)中的元素(一個或多個),然後將其刪除。

Checfk本作更多的jQuery(selector, context)語法 - http://api.jquery.com/jQuery/

0

您可以使用更具體的選擇:http://jsfiddle.net/rWDnM/2/

<table> 
<tr title="test" id="ex1"> 
    <td><div class="move">Hello</div></td> 
    <td>&nbsp;</td> 
    <td>&nbsp;</td> 
</tr> 
<tr id="ex2"> 
    <td><div class="move">Hello2</div></td> 
    <td>&nbsp;</td> 
    <td>&nbsp;</td> 
</tr>  
</table> 

<button id="button1">Move</button> 
<button id="button2">Move 2</button> 
<script> 
$("#button1").click(function() { 
    $("#ex1 .move").remove(); 
}); 

$("#button2").click(function() { 
    $("#ex2 .move").remove(); 
}); 
</script>