[英]Jquery change class on click not working
我有單擊可用於更改類的那些代碼
$(document).ready(function(){
$("div.add").click(function(e){
$.ajax({url: "?action=add&postid=" + $(this).parents('div.box').first().attr("id")})
$(this).removeClass('add').addClass('remove');
});
});
$(document).ready(function(){
$("div.remove").click(function(e){
$.ajax({url: "?action=remove&postid=" + $(this).parents('div.box').first().attr("id")})
$(this).removeClass('remove').addClass('add');
});
});
當我第一次單擊時,div類從<div class="add">
更改為<div class="remove">
並且ajax url有效,但是當我再次從更改的類中單擊時,什么也沒有發生。 (它不會變回添加類)
可能是因為在文檔就緒事件中沒有帶有remove
類的div
元素,所以您的$("div.remove")
返回一個空集合。 解決問題的一種方法是使用事件委托技術:
$(document).on('click', 'div.remove', function() {
// ...
});
但是在這種情況下,我建議使用hasClass
和toggleClass
方法來切換和檢查類名稱:
$(document).ready(function() {
$("div.add").click(function(e) {
var add = $(this).toggleClass('add remove').hasClass('add'),
id = $(this).closest('div.box').attr("id"),
action = add ? 'add' : 'remove',
url = '...';
$.ajax({
url: url
})
});
});
如果在附加事件處理程序.on
不希望監聽事件的元素存在,則最好使用.on
方法附加事件處理程序。 在您的情況下,您可以這樣做:
$(document).on('click', '.add', function() { ... });
$(document).on('click', '.remove', function() { ... });
這稱為事件委托 ,根據我自己的理解, 事件委托將事件處理程序附加到DOM樹中上方的元素,該元素肯定會在頁面加載后存在。 事件將使DOM樹冒泡(除非阻止),在它們所經過的元素中執行所有事件處理程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.