JQuery 停止方法调用中的事件冒泡
我试图了解 jquery 插件结构并编写了以下 HTML 代码,该代码形成了幻灯片的开头:
<div id="bubble" style="width: 200px; height: 200px; background: #ccc;"></div>
<script type="text/javascript">
jQuery.noConflict();
(function($) {
$(function() {
$(document).ready(function() {
$("#bubble").bubble();
});
});
})(jQuery);
</script>
这链接到以下 jquery 插件代码:
(function($){
var i = 0;
var methods = {
mouseup: function(e){
$(this).bubble('next');
e.stopPropagation();
},
mousedown: function(e){
$(this).bubble('next');
e.stopPropagation();
},
next: function(){
console.log(i++);
}
};
$.fn.bubble = function(method){
$(this).bind("mouseup", methods.mouseup)
.bind("mousedown", methods.mousedown);
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
}
};
})(jQuery);
我不知道为什么,但单击气泡框会调用多次迭代下一个:方法。有没有办法限制调用 next: 方法的次数?
I am trying to get my head around the jquery plugin structure and wrote the following HTML code which forms the start of a slideshow:
<div id="bubble" style="width: 200px; height: 200px; background: #ccc;"></div>
<script type="text/javascript">
jQuery.noConflict();
(function($) {
$(function() {
$(document).ready(function() {
$("#bubble").bubble();
});
});
})(jQuery);
</script>
This is linked to the following jquery plugin code:
(function($){
var i = 0;
var methods = {
mouseup: function(e){
$(this).bubble('next');
e.stopPropagation();
},
mousedown: function(e){
$(this).bubble('next');
e.stopPropagation();
},
next: function(){
console.log(i++);
}
};
$.fn.bubble = function(method){
$(this).bind("mouseup", methods.mouseup)
.bind("mousedown", methods.mousedown);
if ( methods[method] ) {
return methods[method].apply( this, Array.prototype.slice.call( arguments, 1 ));
}
};
})(jQuery);
I'm not sure why but clicking the bubble box calls multiple iterations of the next: method. Is there a way to limit the number of calls to the next: method?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您将
mousedown
和mouseup
绑定到next
函数,这将每次点击发送两个next
函数,我不知道我认为你无意这样做。要修复此问题,请删除其中一个绑定,或者仅绑定
click
。You are binding
mousedown
andmouseup
to thenext
function, this will send twonext
functions per click, I don't think you are meaning to do that.In order to fix it, remove one of the binds, or just bind
click
.也许您应该使用 stopImmediatePropagation() 这样您只需记录两次(因为您调用了 next()两次):
小提琴:http://jsfiddle.net/k3FhM/
Maybe you should use stopImmediatePropagation() so that you just log twice (because you call next() twice):
fiddle: http://jsfiddle.net/k3FhM/