JavaScript 不会检测到链接上的单击

javascript does not detect the click on the link

本文关键字:单击 链接 检测 JavaScript      更新时间:2023-09-26

我正在插入链接元素并想分享点击,但我没有得到..测试代码:

<html>
<title></title>
<head>
    <script type="text/javascript" src="https://code.jquery.com/jquery-2.1.1.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $("#teste").click(function(){
               $("body").append($("<a>").text("Element A"));
            });
            $("a").click(function(){
               alert("oi");
            });
        });
    </script>
</head>
<body>
    <input type="button" value="INSERT A" id="teste" />
</body>
</html>

附加事件时,链接不在页面上。这就像在做披萨之前试图吃掉它。单击事件时需要附加事件,或者需要使用事件委派。

$(document).on("click", "a", function(){
    alert("oi");
});

您尝试在创建元素之前注册处理程序,您必须使用委派,即在已经存在的祖先节点上注册事件,并对其进行过滤。

jQuery有一个简单的方法可以做到这一点。

$(document).on('click', 'a', function(){
   alert("oi");
});