2013-03-08 73 views
1

嘗試獲取由ajax內容觸發的事件,其父元素也是ajax加載的。.on('click')與來自另一個ajax內容的ajax內容

<div id="content"><!-- NOT ajax-loaded --> 
    <div id="location"> <!-- #location IS ajax-loaded --> 
     <div id="add_location> <!-- #add_location IS ajax-loaded from a #location event --> 

      <input type="text" id="add_location_city_example" /> 
      <input type="text" id="add_location_state_example" /> 

      <input type="submit" id="add_location_confirm" /> 

     </div> 
    </div> 
</div> 


$(function(){ 
    $('#content').on('click', '#add_location_confirm', function(){ 
    console.log('debug 1'); 
    add_location(); 
    // will not be called 
    }); 

    $('#location').on('click', '#add_location_confirm', function() { 
     console.log('debug 2'); 
     // will not be called either 
     add_location(); 
    }); 
}); 

如果非要的onclick = 「add_location()」 和函數add_location(){的console.log('調試3); }在我的.js中,那麼它顯然會被調用,但是我不能得到$('#add_location_city_example')。val(),因爲它們都不在dom中。

注意:在使用1.9.1

+0

是否'的console.log(「調試1」); 「工作? – j08691 2013-03-08 01:24:49

+0

是的,我使用chrome和console.log工程。我在Chrome中廣泛使用它進行調試,並且從來沒有遇到過問題 – 2013-03-08 01:26:04

+0

嗯,不,我的意思是它實際上是日誌輸出,因爲它後面兩行你說「//不會被調用」,所以我試圖如果console.log運行,但輸出停止或不運行。 – j08691 2013-03-08 01:28:57

回答

1

我一直在使用這一段時間,使得它更容易處理的情況就像你所描述+只有一個,即使是頁面上幾乎所有的點擊任務,其中包括將在未來顯示在頁面上的元素:

$(document).bind('click', function (e) { 
    var target = $(e.target); 
    if (target.is('#content')) { 
     e.preventDefault(); 
     // do whatever 
    } else if (target.is('#location')) { 
     e.preventDefault(); 
     // do whatever else 
    } 
}); 

或在您的情況下,它可能會更喜歡這樣的:

$(document).bind('click', function (e) { 
    var target = $(e.target); 
    if (target.is('#add_location_confirm')) { 
     e.preventDefault(); 
     if (target.closest('#location').length == 0) { // not yet have location injected via ajax 
      // do something 
     } else { 
      // location has been injected, do something else 
     } 
});