2014-04-14 120 views
1

我一直在使用jQuery一段時間,但這個問題從來沒有發生過。非常基本的jQuery

基本上,HTML:

<div class="button three"></div> 
<div id="Content"></div> 

CSS:

.button.three { 
width: 50px; 
height: 50px; 
background: blue; 
} 

.textBlock { 
    background: orange; 
    height: 20px; 
    width: 20px; 
} 

的jQuery:

$(document).ready(function() { 

    $(".button.three").click(function() { 
     $("<div class='textBlock'></div>").appendTo("#Content"); 
    }); 

    $(".textBlock").click(function() { 
     alert("2"); 
    }); 

}); 

見的jsfiddle: http://jsfiddle.net/Brannie19/cQk8t/

爲什麼這不起作用?

---編輯--- 我想知道爲什麼點擊事件.textBlock不會觸發。 dsaa和net.uk.sweet的回答實際上是向我解釋的,所以謝謝你們。

+1

什麼「不工作」? –

+4

[事件處理程序未捕獲[動態生成的元素觸發的事件]]的可能重複(http://stackoverflow.com/questions/12829963/events-triggered-by-dynamically-generated-element-are-not-captured-by -event-hand) –

+0

和[Event binding on dynamic created elements?](http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) –

回答

2

您正在嘗試將偵聽器添加到尚不存在的元素。解決的辦法是委託該事件,其中不使用jQuery方法上存在的父元素(見documentation):

$(document).ready(function() { 

     $(".button.three").click(function() { 
      $("<div class='textBlock'></div>").appendTo("#Content"); 
     }); 

     $("#Content").on('click', '.textBlock', function() { 
      alert("2"); 
     }); 

    }); 

http://jsfiddle.net/YNWX8/

+0

我認爲這是問題,因爲如果我將點擊事件添加到$ 「

」),它會工作。非常感謝:)我無法弄清楚如何工作。 我會upvote你的答案,但我不能夠,因爲我沒有足夠的代表:( – Brannie19

+1

沒有問題,我upvoted你,所以希望你在你的方式;) –