I'm trying to remove the parent item of an <a>
, this is the html:
<div>123321<a class="del" rel="32" href="#">X</a></div>
And this is the code:
$(function()
{
$('.del').click(function(e)
{
$(e).parent().remove();
});
});
But nothing happen, why? JSFIDDLE.
You're passing the event
object to jQuery, not the current element. Use this
in place of e
inside your handler:
$(function() {
$('.del').on('click', function(e) {
e.preventDefault();
$(this).parent().remove();
});
});
In the above example, notice how e
is used to represent the event that occurred, while this
is used to represent the event's target element .
$(function() { $('.del').on('click', function(e) { e.preventDefault(); $(this).parent().remove(); }); });
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <div>123321<a class="del" rel="32" href="#">X</a></div>
(You could use this
as mentioned in the other answer but also you have possibility to use e.target
that refer to the current object also). so instead of passing event e
you could pass the object of the current clicked element using e.target
, check the example below.
$(function() { $('.del').on('click', function(e) { $(e.target).parent().remove(); }); });
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <div>123321<a class="del" rel="32" href="#">X</a></div>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.