2013-04-28 71 views
2

在我的問題有意義之前,有幾件事需要解釋。在我的第一頁,我有一個主要的div,我使用jquery load()方法從另一個頁面加載標記。我正在加載的HTML鏈接到我的腳本所在的.js頁面。 js頁面是我操縱主div內容的地方。 在我的js頁面上,我循環訪問一個從數據庫中提取的變量數組,並將它們追加()到主div。在for循環中,我將每行包裝在它自己的div中幷包含一個錨標籤。錨點標記是我想要附加click()方法,所以我可以調用一個函數,一旦它被點擊。我已經嘗試了父類>子選擇器等,但沒有任何作用的錨標記。我的代碼:jquery click()事件不適用於附加的html標記

//this is the query to my parse database 

query.find({ 
    success: function(results) { 
    for (i = 0; i < results.length; i++){ 

     activity = results[i].get("activity"); 
     scene = results[i].get("location"); 
     neighborhood = results[i].get("neighborhood"); 
     date = results[i].get("date"); 
     details = results[i].get("details"); 
     time = results[i].get("time"); 
     search.push([activity, scene, neighborhood, date, details, time]); 

     for (i = 0; i < search.length; i++) { 

      //append each row of results to mainDiv inside of their own div with an anchor tag at the end of each row. 
      //when the anchor tag is clicked I want to call a function, but none of the selectors I've tried have worked. 

      $('#mainDiv').append("<div id='event'>" + search[i].join(' ') + "<a href='#' id='interested'>Interested?</a></div>"); 
     } 

    };// closes for loop 
    },//closes success function 
    error: function(error) { 
    alert("Error: " + error.code + " " + error.message); 
    } 
}); //closes find 

回答

2

我在這裏找到答案: Newly appended div doesn't inherit event handler in document ready

快捷的事件處理程序(如點擊(),鼠標懸停()等),只適用於它們提供給DOM上的元素頁面加載。當附加元素動態的,你必須將事件附加到一個靜態的父元素,並提供您希望委派的事件,像這樣的過濾器:

這是我的解決方案:

$("#mainDiv").on('click', '.interested', function(){ 
     alert("working"); 
    });