在文档上使用removeEventListener不起作用? [英] Using removeEventListener on document does not work?
问题描述
看看这段代码:
$(document).ready(function() {
document.getElementById(sliderId).onmousedown = sliderMouseDown;
});
function sliderMouseDown() {
document.onmousemove = sliderMouseMove;
document.onmouseup = sliderMouseUp;
}
function sliderMouseMove() {
$('#test').html("sliding");
}
function sliderMouseUp() {
$('#test').html("not sliding");
document.removeEventListener('mousemove', sliderMouseMove, false);
document.removeEventListener('mouseup', sliderMouseUp, false);
}
一切正常,直到sliderMouseUp函数被调用。现在,该函数调用好了,#test-div表示不滑动,但是如果我之后将文件移动到文档中,则会再次在#test-div中显示滑动,就像removeEventListener函数不行我在这里做错了吗?
Everything works as it should, until the sliderMouseUp function is called. Now, the function is called alright, and the #test-div says "not sliding", but if I move my mouse around in the document afterwards, it displays "sliding" in the #test-div again, like if the removeEventListener function does not work. Am I doing something wrong here?
推荐答案
如果jQuery是一个选项,似乎是因为你使用它这个:
If jQuery is an option, and seems it is since you're using it, do this:
$(function() {
$("#" + sliderId).mousedown(function() {
$(document).mousemove(function() {
$("#test").html("sliding");
}).mouseup(function() {
$("#test").html("not sliding");
$(document).unbind("mousemove mouseup");
});
});
});
使用jQuery事件模型会导致很少的头发拉扯,让它照顾跨浏览器和事件怪癖。
Using the jQuery event model will result in a lot less hair-pulling, let it take care of the cross-browser and event quirks for you.
这篇关于在文档上使用removeEventListener不起作用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!