2013-04-26 41 views
0

我正在通過javascript向我的文檔添加一些HTML。我也通過這個javascript函數爲我的HTML添加一個按鈕。我想要這個按鈕有一個事件監聽器,但是這似乎不適用於用javascript添加的元素。有沒有可能解決這個問題?如何獲得一個事件偵聽器來處理通過javascript添加到我的html中的元素?

我的JS:

$('#content-overview li').on('click',function(){ 

      // Clear previous videos 
      $('.content-overview-row').remove(); 

      // Insert new video 
      var vimeoId = $(this).data('vimeo');    
      var html = '<li class="content-overview-row"><div class="content-overview-video"><iframe src="http://player.vimeo.com/video/'+vimeoId+'" width="950" height="534"></iframe><a id="close-video"></a></div></li>'; 

      // Find end of row and insert detailed view 
      var nextRow = $(this).nextAll('.first-in-row:first'); 

      if(nextRow.is('li')){ 
       nextRow.before(html); 
      } 
      else{ 
       //last row 
       if($(this).hasClass('first-in-row')) 
       { 
        //first item clicked in last row 
        $(this).before(html); 
       } 
       else{ 
        $(this).prevAll('.first-in-row:first').before(html); 
       } 
      }   

      return false; 

      $('#close-video').click(function() { 
       console.log("works"); 
      }); 
    }); 

特寫視頻的關閉按鈕我在說什麼。

+0

在調用'.click()' – zeroflagL 2013-04-26 07:25:28

回答

2

您需要點擊事件,其中將存在於當頁面加載的DOM元素進行綁定,並委派動態添加的元素,像這樣:

$(document).on('click', '#close-video', function() { 
    ... 
}); 

你應該爲最接近的元素來改變document到您的#close-video,這樣它就不必冒泡到document

此外,你returning false;之前的#close-video點擊處理程序,以便代碼永遠不會執行。將它移動到您的#content-overview li點擊處理程序之外。

+0

之前,函數返回您的答案解決了我的問題。非常感謝 :) – 2013-04-26 07:27:08

相關問題