zbr*_*zbr 6 html javascript jquery
假设我有这个HTML ...
<button class="btn-remove-this">Remove this</button>
<button class="btn-remove-that">Remove that</button>
<button class="btn-remove-some-other-thing">Remove some other thing</button>
<!-- and many more 'Remove ...' buttons -->
Run Code Online (Sandbox Code Playgroud)
......还有这个JavaScript.
$(function() {
$('.btn-remove-this').click(function() {
functionWhichRemovesThis();
}
$('.btn-remove-that').click(function() {
functionWhichRemovesThat();
}
$('.btn-remove-some-other-thing').click(function() {
functionWhichRemovesSomeOtherThing();
}
// and many more click handlers
});
Run Code Online (Sandbox Code Playgroud)
现在我想在删除所有这些内容之前提示用户进行确认对话.有没有办法在不添加和调用confirm每个单击处理程序的情况下执行此操作?
我有一些想法,比如将一个类添加到所有不同的按钮(比方说btn-remove),然后添加一个单击处理程序,如下所示:
$('.btn-remove').click(function() {
if (confirm('Are you sure you want to remove this?')) {
// execute the body of the "more specific" click handler
} else {
// prevent the body of the "more specific" click handler from executing
}
}
Run Code Online (Sandbox Code Playgroud)
小智 1
您可以为不同的按钮编写不同的单击处理程序,并调用通用检查函数,您想要调用的函数是否有一个参数,然后单击确定,您可以调用该回调函数。
$('.btn-remove-this').click(function() {
check(functionWhichRemovesThis);
});
$('.btn-remove-that').click(function() {
check(functionWhichRemovesThat);
});
$('.btn-remove-some-other-thing').click(function() {
check(functionWhichRemovesSomeOtherThing);
});
function check(callback){
if (confirm('Are you sure you want to remove this?')) {
callback();
} else {
// prevent the body of the "more specific" click handler from executing
}
}
Run Code Online (Sandbox Code Playgroud)
这也是一个办法。这样您就不必对代码进行太多修改。