根據jQuery文檔,event.stopPropagation();
應該停止事件冒泡。在下面的腳本中,當我刪除event.stopPropagation();
時,該函數將刪除ul
元素代碼塊,包括它的所有子代。我加event.stopPropagation();
停止冒泡,但它返回以下錯誤:如何在刪除元素時防止冒泡的jQuery事件?
TypeError: undefined is not an object (evaluating 'event.stopPropagation')
以下是HTML和jQuery代碼:
$('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 the dog
<span class='remove'></span>
</li>
<li class='todo-item'>Cut the lawn
<span class='remove'></span>
</li>
<li class='todo-item'>Laundry
<span class='remove'></span>
</li>
</ul>
參考文獻:
你可以像'event.originalEvent.stopPropagation()'一樣訪問'event.originalEvent'中的原始DOM事件。 – rupps
沒有事件傳遞給你的'hide'函數,因爲它不是一個事件。在'click,function(event)'中放入'event' – Adjit
'hide()'函數沒有事件,'.on('click',function(event){...'does – adeneo