2015-11-01 125 views
0

對於我正在處理的項目,我將記錄添加到列表中。但添加內容中的按鈕不會執行它應該執行的JavaScript。Javascript未執行添加html

我已經做了一個潦草的東西 - 儘可能簡單 - 來演示。

按鈕「點擊一些內容」像我期望的警報火災。按鈕'一些其他內容點擊'不。

我懷疑這與html不在那裏負載...但我無法解決如何解決這個問題。

反正......如果你們願意幫助...這裏是代碼:

<!DOCTYPE html> 
<html> 
<head> 
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"> 
    <title>scribble</title> 
    <script type='text/javascript' src='//code.jquery.com/jquery-1.8.3.js'></script> 

    <script type='text/javascript'> 
     //<![CDATA[ 
     $(function() { 

      $('.clickme') 
       .click(function() { 
        list = $(this).parents('.container').find('.list'); 
        list.prepend('<div class="record"><button class="record_button">some other content to click</button></div>') 
        alert('added a record'); 
       }); 

      $('.record_button') 
       .click(function() { 
        alert('content clicked'); 
       }); 


     });//]]> 

    </script> 

</head> 
<body> 
    <div class='container'> 
     <button class='clickme'>add record</button> 
     <div class='list'> 
      <div class='record'> 
       <button class='record_button'>some content to click</button> 
      </div> 
     </div> 
    </div> 
</body> 

</html> 
+0

發現這個http://stackoverflow.com/questions/14269587/how-to-execute-script-code-in-a-javascript-append但我無法弄清楚如何使用這個 – Peter

回答

1

嘗試

$('.clickme').on('click',function().. 

監聽器不用於添加的元素工作,除非你給他們打電話像這樣。

jQuery .on()