我正在使用AngularJS動態生成大量內容的網站上工作。我需要獲取使用jQuery動態生成的元素的屬性,但我在這樣做時遇到了麻煩。我已經發現我需要使用.on
方法來點擊而不是.click
。我的問題是在.on
方法中找到等效的$(this)
。jQuery在動態生成內容時獲取單擊元素的屬性
這裏是我的代碼:
$(document.body).on('click', 'a.card-topic-link' ,function(e) {
e.preventDefault(); // Prevent default action - this works
console.log('The click works!'); // This fires and works just fine
var cardTopicLink = $(this).attr('data-topic-link'); // This is where the problem lies
console.log(cardTopicLink); // This is undefined
}); // End on click
正如我前面所說,這並不爲.click
工作動態內容不工作:
$('a.card-topic-link').click(function(e) {
e.preventDefault(); // Prevent default action
var cardTopicLink = $(this).attr('data-topic-link');
console.log(cardTopicLink);
});
我覺得有一個簡單的解決方案這個問題我很難找到。這個問題的關鍵是,這是處理動態內容。
讓我知道你是否有任何想法。
你如何設置元素的'data-topic-link'屬性? – Frxstrem
它被設置在存儲在數據庫中的HTML中,並基本上通過AngularJS打印到屏幕上。它看起來像這樣並正在正確地工作'data-topic-link =「text」'。 – mbacon40
爲什麼你不使用'ng-click'並傳遞任何數據生成的屬性值呢?需要提供[mcve] – charlietfl