如何通过jquery .html创建一个href,然后使用它的事件

How create a href through jquery .html and next use its event?

本文关键字:然后 href 事件 一个 html jquery 何通过 创建      更新时间:2023-09-26

我的问题描述如下:

我有这个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); 
} 

但是这行不通…

你能帮我吗?

谢谢你提前!

您应该使用事件委托 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">

你应该这样做。

$("#table").on('click','a[name="example"]',function() {
    var example= $(this).attr("class");
    alert(example); 
});
 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE>
<html>
  <body>
  <div id="table">
    <a name="example" class="one">One</a>
    <a name="example" class="two">Two</a>
  </div>
  </body>
  
  
</html>