JQuery停止从方法调用冒泡的事件

时间:2011-09-21 16:10:02

标签: jquery plugins event-bubbling

我试图了解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);

我不确定为什么但是点击气泡框会调用下一个方法的多次迭代。有没有办法限制对下一个方法的调用次数?

2 个答案:

答案 0 :(得分:1)

您将mousedownmouseup绑定到next函数,每次点击会发送两个next个函数,我认为您不会这样做

要修复它,请删除其中一个绑定,或者只绑定click

答案 1 :(得分:0)

也许您应该使用stopImmediatePropagation(),这样您只需记录两次(因为您调用next()两次):

(function($){
var i = 0;

var methods = {
    mouseup: function(e){
        $(this).bubble('next');
        e.stopImmediatePropagation();
    },
    mousedown: function(e){
        $(this).bubble('next');
        e.stopImmediatePropagation();
    },
    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);

小提琴:http://jsfiddle.net/k3FhM/

相关问题