鍍金池/ 問答/HTML/ 關(guān)于 jq的off事件,只想解除當(dāng)前對(duì)象的事件不起作用

關(guān)于 jq的off事件,只想解除當(dāng)前對(duì)象的事件不起作用

  1. 問題描述 :
    因?yàn)槲业脑创a是從ajax中加載的,用綁定事件只能用事件委托 。

這里貼出來的代碼是demo。
我要實(shí)現(xiàn)的效果 是針對(duì)當(dāng)前的p單擊兩次,off事件生效。
$(this).off('mouseleave click');//這行代碼不起作用
$(document).off('mouseleave click','p');//這行卻對(duì)于所有的都p都起作用,可是只想對(duì)當(dāng)前p起作用怎么辦啊 。
請(qǐng)大神幫忙看看。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>菜鳥教程(runoob.com)</title>
<script src="http://cdn.static.runoob.com/libs/jquery/1.10.2/jquery.min.js">
</script>
<script>
$(document).ready(function(){
    var x=0;
    $(document).on('click' , 'p' , function(event){
        $(this).animate({fontSize:"+=5px"});
        x++;
        if (x>=2)
        {
            alert(this);
            $(this).off('mouseleave click');//這行代碼不起作用
            $(document).off('mouseleave click','p');//這行卻對(duì)于所有的都p都起作用,可是只想對(duì)當(dāng)前p起作用怎么辦啊            
        }
        
    });
    $(document).on('mouseleave' , 'p' ,function(event){
        alert("你離開了");
    })
});
</script>
</head>
<body>

<p>1. 點(diǎn)擊這個(gè)段落放大字體,只會(huì)放大兩次。</p>
<p>2. 點(diǎn)擊這個(gè)段落放大字體,只會(huì)放大兩次。</p>
<p>3. 點(diǎn)擊這個(gè)段落放大字體,只會(huì)放大兩次。</p>
</body>
</html>

演示 :http://sandbox.runjs.cn/show/...

回答
編輯回答
短嘆

事件委托, 事件不是綁定在P上的, 是綁定在 document 上的, 所以要解除都解除了.

試試這么做把

      $(document).on('click', 'p', function(event) {
        var $this = $(this);
        var times = $this.data('times') || 0;
        if(times < 2){
          $this.animate({
            fontSize: "+=5px"
          }).data('times', ++times);
        }
      });
2017年6月4日 18:14
編輯回答
故人嘆
$(document).on('click' , 'p' , function(event){
        if (x>=2)
        {
            return         
        }
        $(this).animate({fontSize:"+=5px"});
        x++;
    });
2017年3月13日 00:00