我有一个有趣的情况。我有多个点击事件附加到一个元素。
在事件 1 之后,我需要删除事件 2,但保留事件 1。
这是我的:
$('.square').on('click', grow);
$('.square').on('click', nameReset);
var nameReset = function () {
alert(this.className);
}
var grow = function () {
$(this).toggleClass('grow');
$(this).off('click');
}
换句话说,我需要保留 grow 函数,但在事件触发后删除 nameReset。
.square {
height: 100px;
width: 100px;
border: 1px solid;
display :inline-block;
transition: all 2s;
}
.grow {
width: 150px;
height: 150px;
}
.red { background-color: red; }
.blue { background-color: blue; }
最佳答案
两种选择:
在删除事件时指定函数(即
$(this).off('click', nameReset)
)。A handler can be removed by specifying the function name in the handler argument. When jQuery attaches an event handler, it assigns a unique id to the handler function.
var nameReset = function () { alert(this.className); } var grow = function () { $(this).toggleClass('grow'); $(this).off('click', nameReset); } $('.square').on('click', grow); $('.square').on('click', nameReset);
或者,您可以 namespace the events , (
$(this).off('click.square.nameReset')
) 以删除所需的事件:var nameReset = function () { alert(this.className); } var grow = function () { $(this).toggleClass('grow'); $(this).off('click.square.nameReset'); } $('.square').on('click.square.grow', grow); $('.square').on('click.square.nameReset', nameReset);
关于javascript - 根据事件有条件地阻止事件删除,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28491439/