2016-09-29 31 views
0

我已閱讀3個類似問題的答案,但我無法將它們應用於我的網站。我通過ajax加載html頁面。我知道我無法在document.ready期間應用$(「a」)。click()事件,因爲ajax內容鏈接在dom中不存在。我想過試圖在$ .get響應中添加事件,但在$ .get內部添加$ .get來點擊看起來像是瘋狂。我嘗試使用$(document).on('click','a',fn())也不起作用。

$(document).ready(function() { 

    $(document).on('click', 'a', function(e) { 
     e.preventDefault(); 
     $.get($(this).attr("href"), function(data) { 
     $("#mainSection").html(data); 
     }); 
     return false; 
    }); 
}); 

mainSection是index.html上的div id(與代碼運行時相同)。所有鏈接的處理就像通常點擊一樣,沒有腳本錯誤。

+0

[動態創建的元素上的事件綁定?]可能的重複?(http://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – empiric

+0

謝謝經驗!我實際上試圖從該頁面實現6個不同的答案,並且無法使其工作:( –

+0

您能設置一個示例(使用html)來顯示您的標記在前後的樣子嗎? – empiric

回答

0

你的代碼裏沒有明顯的錯誤。無論你的腳本是在錯誤的地方,還是你在其他方面有錯誤,或者是別的。

工作例如:

var content = $('.content'); 
 
var newAnchor = function() { 
 
\t content.append('<p><a href="https://google.com">' + new Date().getTime() + '</a></p>') 
 
} 
 
$('button').on('click', newAnchor); 
 
$(document).on('click', 'a', function(e) { 
 
\t e.preventDefault(); 
 
    alert('No-no!'); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="content"></div> 
 
<button>Add new anchor</button>

我建議你把這個腳本動態內容區域#mainSection之外