2012-07-12 48 views
0

Here's一個演示問題的小提琴。我將一個元素點擊到'html'元素後添加一個jQuery綁定。我不希望'one'事件處理程序在下次點擊之前觸發,但會觸發添加綁定的點擊。這似乎不是一個問題,如果它是'one'事件處理程序添加到的更具體的元素,但它發生在我使用'html'或'body'作爲元素時,這正是我想要做的。爲什麼jQuery在添加到元素時立即觸發?

這對我來說沒有意義,我認爲第一次點擊會爲下一次點擊添加一次,並且它不會觸發點擊鏈接。順便說一下,我的實際問題可能會以更好的方式解決,但是我遇到了這個問題,並且很好奇爲什麼它沒有按照我的預期工作。


代碼:

HTML:

<div id='hello'>hello</div> 
<a class="title" href="#">this example</a> is a test​ 

JS:

$(function() { 
    $('a.title').click(function() { 
     var htmlClickBind = function (e) { 
      console.log('clicked on html, e.target = ' + e.target); 
      console.log(e.target == ''); 
      if (!$(e.target).is('a')) { 
       console.log('cleared click event'); 
      } 
      else { 
       $('html').one('click', htmlClickBind); 
      } 
     }; 

     $('html').one('click', htmlClickBind); 
    }); 
});​ 
+0

始終包括相關的代碼和標記**的問題本身**,不只是鏈接:http://meta.stackexchange.com/questions/118392/add-stack-overfow-faq-entry-or-similar-for-code-question-question- – 2012-07-12 16:16:21

+0

@TJCrowder你可以輕鬆地複製/粘貼.... – Neal 2012-07-12 16:18:39

+0

@Neal它是以防止鏈接腐爛B) – Snuffleupagus 2012-07-12 16:19:43

回答

6

click事件a.target元素上冒泡到html元素,你的(只是 - 添加)處理程序看到它。

爲了防止這種情況,在您的a.targetclick處理器(或return false,這確實stopPropagationpreventDefault)使用event.stopPropgation

更新後的代碼(見註釋):Live copy

$(function() { 
    // Accept the event arg ----v 
    $('a.title').click(function(e) { 
     // Stop propagation 
     e.stopPropagation(); 
     var htmlClickBind = function (e) { 
      console.log('clicked on html, e.target = ' + e.target); 
      console.log(e.target == ''); 
      if (!$(e.target).is('a')) { 
       console.log('cleared click event'); 
      } 
      else { 
       $('html').one('click', htmlClickBind); 
      } 
     }; 

     $('html').one('click', htmlClickBind); 
    }); 
});​ 
+0

好的,這對我來說現在是有意義的,因爲事件冒起來了。謝謝您的幫助。 – rosscj2533 2012-07-12 16:31:09

+0

@ rosscj2533:很高興!很高興這有幫助。最好, – 2012-07-12 16:41:34

相關問題