我在 html 表格中有一个元素:
<td><a id="href0" href="#" data-productid="0">Product 1</a></td>
我需要获取“data-productid”属性的值
目前我有这个代码:
$(document).ready(function(){
$('#href0').click(function(event) {
event.preventDefault()
console.log(this.dataset.productid)
return false;
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<td><a id="href0" href="#" data-productid="0">Product 1</a></td>
控制台中没有打印任何内容。
我正在使用 Handlebars
最佳答案
我们设法确定您正在使用 Handlebars 模板
可能的情况是,当您编译 Handlebars 时,您的链接会动态插入。
如果是这种情况,您需要委托(delegate),那么这个问题是 Event binding on dynamically created elements? 的重复问题
$(document).ready(function(){
// document or the nearest STATIC container
$(document).on('click','[data-productid]',function(event) {
event.preventDefault()
console.log(this.dataset.productid)
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<td><a id="href0" href="#" data-productid="0">Product 1</a></td>
<td><a id="href0" href="#" data-productid="1">Product 2</a></td>
关于javascript - 使用 jquery 从 html <a> 元素获取数据集项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56142133/