<% (1..3).each do %>
<p id="input">
<input type="text" name="somename"/>
<a class="remove" >Remove</a>
</p>
<% end %>
jQuery:
var $remove=$(".remove")
$remove.click(
function(){
开发者_JAVA技巧 $(this).parent().remove();
alert($remove.length);
})
It always alerts 3
, why? Did I remove the class remove
correctly?
Removing the element from the DOM doesn't destroy the reference held in $remove
. Try alert($(".remove").length)
instead.
Edit: Here's a fiddle.
$remove
is pointing to the value of $(".remove")
when it is defined, it is by value not by reference. This means if $(".remove"
) changes it will not be reflected in $remove
. You need to query the element again before looking at the length.
It's always three because you save the array into $remove
var $remove=$(".remove")
$remove.click(function() {
$(this).parent().remove();
alert($remove.length); // saved reference to $('.remove') <-- original call still
})
$remove collection of elements won't be updated automatically. However you can run the selector once more to get the result you want:
$(".remove").click(
function(){
$(this).parent().remove();
alert($(".remove").length);
}
)
精彩评论