0

I have this code below:

 jQuery.noConflict();
    var x=0;
    myw=0;
    oin="";
    jQuery(document).ready(function () {
        if(x >3){
            $("img:odd").unbind("mouseenter");
            return false;
        }        
        jQuery("img:odd").mouseenter(function(e) {
          //  oin="";
            console.log(e);
            console.log(this);
            console.log(this.src);
            oin=this.src;
            this.src="snowdrop.png";
            myw=this.width;
            this.width=100;
            x=x+1;
            console.log(x);
           jQuery(this).css("opacity", 0.5);
        }).mouseout(function(e) {
            this.width=myw;
            this.src=oin;
           jQuery(this).css("opacity", 1.0);
        });


    });

The code runs fine but what I want to do is after 3 mouseovers(mouseenter) I want to disable the mouseenter event. I can't figure out how to unbind it?

Thanks, Jim

4

3 に答える 3

2

アンバインド ロジックを mouseout イベント ハンドラ内に移動する必要があります。

    }).mouseout(function(e) {
        this.width=myw;
        this.src=oin;
        jQuery(this).css("opacity", 1.0);
        if(x == 3){
            $("img:odd").unbind("mouseenter");
            $("img:odd").unbind("mouseout");
        }
    });

より正確にするために、おそらく mouseenter ハンドラーでこれを行う方が良いでしょう

    jQuery("img:odd").mouseenter(function(e) {
      //  oin="";
        console.log(e);
        console.log(this);
        console.log(this.src);
        oin=this.src;
        this.src="snowdrop.png";
        myw=this.width;
        this.width=100;
        x=x+1;
        console.log(x);
        jQuery(this).css("opacity", 0.5);
        if(x == 3){
            $("img:odd").unbind("mouseenter");
            $("img:odd").unbind("mouseout");
        }
    })
于 2012-08-29T13:21:05.233 に答える
1

on()これにはandoff()を次のように使用します。

(function($) {
    var x=0,
        myw=0,
        oin="";

    $('img:odd').on({
        mouseenter: doStuff, //bind a function, it's easier to rebind
        mouseleave: function() {
           this.width=myw;
           this.src=oin;
           $(this).css("opacity", 1.0);
        }
    });


    function doStuff(e) {
        var elem = e.target;
        if (x>3) {
            $(elem).off('mouseenter'); //unbind the event
            return;
        }else{
            x++;
            oin=elem.src;
            elem.src="snowdrop.png";
            myw=elem.width;
            elem.width=100;
            $(elem).css("opacity", 0.5);
        }
    }
})(jQuery);​
于 2012-08-29T13:26:12.240 に答える
0

これに完全に答える質問があります: jQuery でイベント ハンドラーを削除する最良の方法は?

例を次に示します。

単一のイベントを追加してから削除したい場合 (追加された可能性のある他のイベントを削除せずに)、イベントの名前空間を使用できます。

$('#myimage').bind('click.mynamespace', function() { /* Do stuff */ });

イベントだけを削除するには:

$('#myimage').unbind('click.mynamespace');
于 2012-08-29T13:21:53.587 に答える