嗯,我的问题描述如下:
我有这个 JavaScript 代码,以便在表中创建 href:
$('#table').html('<a name="example" class="one">One</a><a name="example" class="two">Two</a>');
然后我想知道我按下了哪个 a
标签......类似这样:
$("a[name=example]").click(function(e) {
var example= $(this).attr("class");
alert(example);
}
但这不起作用...
你能帮我吗?
谢谢4提前!
最佳答案
您应该使用事件委托(delegate) on()
将点击事件附加到由脚本动态添加到页面的新 DOM(a
标记):
$("#table").on('click','a[name=example]',function(e) {
var example= $(this).attr("class");
alert(example);
})
希望这有帮助。
$('#table').html('<a name="example" class="one">One</a><br><a name="example" class="two">Two</a>');
$("#table").on('click','a[name=example]',function(e) {
var example= $(this).attr("class");
alert(example);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="table">
关于javascript - 如何通过 jquery .html 创建 href 并接下来使用它的事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40469751/