简体   繁体   English

带有jQuery的锚标签不起作用

[英]Anchor tag with jquery not working

Calling a jquery with dynamically generated anchor tag is not working. 使用动态生成的锚标记调用jquery无效。 Whereas the same with hard coded anchor tag the jquery is working fine. 而与硬编码的锚标签相同,jQuery运行正常。

Code: 码:

<!DOCTYPE html>
<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js">      </script>
    <script>
    $(document).ready(function(){

        var value = "HI!!!";
        $("button").click(function(){
            $("#box").html("<a class='dynamic' href='#' dataid='"+value +"'>Generate</a>");
        });
        $(".hardcode").click(function () {
            alert("Calling function");
        });
        $(".dynamic").click(function () {
            alert("ggsss function");
        });

    });
    </script>
</head>
<body>
    <a class="hardcode" href="#" dataid="sss">Generate</a>
    <button>Change content of all p elements</button>

    <div id="box">
    </div>
</body>
</html>

Since the dynamic anchor tag class is added dynamically, you will need to use event delegation to register the event handler like: 由于dynamic锚标记类是动态添加的,因此您将需要使用事件委托来注册事件处理程序,例如:

// New way (jQuery 1.7+) - .on(events, selector, handler)
$('#box').on('click', '.dynamic', function(event) {
    event.preventDefault();
    alert("ggsss function"); 
});

This will attach your event to any anchors within the #box element, reducing the scope of having to check the whole document element tree and increasing efficiency. 这会将您的事件附加到#box元素中的所有锚点,从而减少了必须检查整个document元素树的范围并提高了效率。

Fiddle Demo 小提琴演示

More Info: 更多信息:

Use $(document).on("click") for dynamically generated element $(document).on("click")用于动态生成的元素

 var value = "HI!!!"; $("button").click(function(){ $("#box").html("<a class='dynamic' href='#' dataid='"+value +"'>Generate</a>"); }); $(document).on("click",".hardcode",function () { alert("Calling function"); }); $(document).on("click",".dynamic",function () { alert("ggsss function"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script> <a class="hardcode" href="#" dataid="sss">Generate</a> <button>Change content of all p elements</button> <div id="box"> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM