javascript - How to prevent jQuery event from bubbling when removing element? -
according jquery documentation, event.stoppropagation();
should stop event bubbling. in following script, when remove event.stoppropagation();
function removes ul
element code block including it's children. added event.stoppropagation();
stop bubbling returns following error:
typeerror: undefined not object (evaluating 'event.stoppropagation')
the following html , jquery code:
$('span.remove').on('click', function() { $(this).parent().hide(500, function(event) { event.stoppropagation(); $(this).parent().remove(); }); });
.todo-list { list-style: none; padding: 0px; } .todo-item { border: 2px solid #444; margin-top: -2px; padding: 10px; cursor: pointer; display: block; background-color: #ffffff; } .remove { float: right; font-family: helvetica, arial, sans-serif; font-size: 0.8em; color: #dd0000; } .remove:before { content: 'x'; } .remove:hover { color: #ffffff; } .todo-item::after:hover { background-color: #dd0000; color: white; } .todo-item:hover { background-color: #0eb0ff; color: white; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class='todo-list'> <li class='todo-item'>4l 2% milk <span class='remove'></span> </li> <li class='todo-item'>butter, unsalted <span class='remove'></span> </li> <li class='todo-item'>dozen eggs <span class='remove'></span> </li> <li class='todo-item'>walk dog <span class='remove'></span> </li> <li class='todo-item'>cut lawn <span class='remove'></span> </li> <li class='todo-item'>laundry <span class='remove'></span> </li> </ul>
references:
you have event
object click()
callback. if @ jquery hide()
api docs, complete callback doesn't passed event undefined, the click()
handler on other hand gets passed event object. need change javascript to:
$('span.remove').on('click', function(event) { event.stoppropagation(); $(this).parent().hide(500, function() { $(this).parent().remove(); }); });
the reason whole list gets removed issue. reference parent()
twice targeting ul removed, rid of 1 of parents (the scope of $(this)
changes parent in hide callback). edit code is:
$('span.remove').on('click', function(event) { event.stoppropagation(); $(this).parent().hide(500, function() { $(this).remove(); }); });
it's true propagation of event, doesn't have ul
being hidden whole can remove event.stoppropagation()
line. final code being:
$('span.remove').on('click', function() { $(this).parent().hide(500, function() { $(this).remove(); }); });
Comments
Post a Comment