我在页面上有一个带有 next-main-button
类的按钮。
页面加载时,会显示一个模式,并且有一个带有 look-task-again
类的按钮。如果我单击它,我想从下一个按钮中删除 next-main-button
类并添加此类 next-task-error
这是下一个按钮:
<button type="button" class="btn btn-default next-main-button" id="next-button" >Next</button>
当点击模态按钮时执行该事件,这里删除了 next-main-button 并添加了 next-task-error。
$(".look-task-again").off("click").on("click", function(){
$('#error-popup-message').modal('hide');
$("#next-button").removeClass("next-main-button");
$("#next-button").addClass("next-task-error");
});
如果我检查元素,类会发生更改,但如果我单击下一个按钮,则会执行已删除类的事件:
$('.next-main-button').off("click").on("click", function(){
nextButtonClick();
});
不是这个:
$(".next-task-error").off("click").on("click", function(){
errorButtonClick();
});
我尝试使用取消绑定(bind)方法并再次绑定(bind)按钮,我是这样做的:
$("#next-button").removeClass("next-main-button").unbind( "click" );
$("#next-button").addClass("next-task-error").bind( "click" );
这样下一步按钮就被停用了,什么也没有发生!有人可以帮我吗?
最佳答案
用于获取绑定(bind)点击处理程序的元素的选择器(即 .next-task-error
或 .next-main-button
)仅是执行一次,并传递一个或多个元素。
然后,您将点击处理程序绑定(bind)到这些元素,但该绑定(bind)不知道您用于获取这些元素的选择器。绑定(bind)是直接在元素上完成的,并且不再验证它们的类(或您可以使用的任何其他选择器)。
为了使其更加动态,您可以 (1) 使用事件委托(delegate),或 (2) 在事件发生时测试单击的元素的类,或 (3) 在条件更改时更改处理程序。
1。事件委托(delegate):
$(document).on("click", ".next-main-button", function(){
nextButtonClick();
});
$(document).on("click", ".next-task-error", function(){
errorButtonClick();
});
相同的较短版本,使用链接:
$(document).on("click", ".next-main-button", nextButtonClick)
.on("click", ".next-task-error", errorButtonClick);
2。处理程序中的测试类:
$('#next-button').on("click", function(){
if($(this).is('.next-main-button')) {
nextButtonClick();
} else {
errorButtonClick();
}
});
3。状态更改时更改处理程序
这就像您尝试做的那样:当条件发生变化时重新绑定(bind)正确的处理程序:
// set initial click handler
$('#next-button').on("click", function(){
nextButtonClick();
});
$(".look-task-again").on("click", function(){
$('#error-popup-message').modal('hide');
$("#next-button").removeClass("next-main-button");
$("#next-button").addClass("next-task-error");
// replace click handler:
$('#next-button').off("click").on("click", function(){
errorButtonClick();
});
});
较短的版本,使用链接:
// set initial click handler
$('#next-button').on("click", nextButtonClick);
$(".look-task-again").on("click", function(){
$('#error-popup-message').modal('hide');
$("#next-button").removeClass("next-main-button")
.addClass("next-task-error")
.off("click")
.on("click", errorButtonClick);
});
关于javascript - 在按钮 jquery 中删除并添加一个类,无法使其工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39332545/