【发布时间】:2017-01-19 00:59:45
【问题描述】:
我有两个链接的鼠标事件:
$('body > form').on("mousedown", function(e){
//Do stuff
}).on("mouseup", function(){
/*More stuff, including
window.addEventListener(...
*/
});
但是,当我尝试从另一个外部函数off() 时,我只能off() mousedown,但不能mouseup,其功能仍然有效。
嵌套的addEventListener 会阻止我取消它的事件吗? (
顺便说一句,我怎么做都没关系
链:($().off().off();),或解链($().off(); $().off();),或组合($().off(A B);)或反转(A B B A)元素;始终如一地,off(mousedown) 有效,但从来没有off(up)。
这是我的完整 JS 代码:
(有问题的部分是第二个脚本,在最后:)
<script>
function comment() {
$('body > form').on("mousedown.markerPlacer", function(e){
//Place the cursor marker on the screen
var newComment2 = $('<div id="newComm" class="marker" class="deg45" ↑</div>');
$('form').append(newComment2);
}).on("mouseup", function(){
//Now use the Q-key to rotate the marker.
window.addEventListener("keydown", extraKey, false);
window.addEventListener("keyup", keysReleased2, false);
function extraKey(e) {
var deg = e.keyCode;
if (deg == 81) { //81 is the keycode, which codes for Q
$('#newComm').attr('class', 'marker').addClass('deg0');
} else {
return false;
};
e.preventDefault();
};
function keysReleased2(e) {
e.keyCode = false;
};
});
};
</script>
<script>
function dismissComment() {
$('body > form').off("mousedown mouseup");
}
</script>
【问题讨论】:
-
因为 .on 不返回任何内容。
-
提供minimal reproducible example。如果没有适当的代码上下文,我们无法看到您如何尝试使用
off() -
@Bindrid,这是什么意思,为什么会有所不同,因为它们都是 .on 事件?
-
@charlietfl,当然,但是 M-C-V 的答案需要我几分钟才能完成。
-
我猜你希望
off()会删除你在on()中创建的任何监听器......但事实并非如此。一旦你添加了一个监听器,它就会一直存在,直到它被移除
标签: jquery chaining mousedown event-listener mouseup