我正在使用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