简体   繁体   English

JavaScript在页面加载后仅运行一次

[英]JavaScript runs only once after page loading

This script is triggered only once when the page loads. 页面加载时仅触发一次此脚本。 The page has loaded, click the link, the data came from. 该页面已加载,单击链接,数据来自。 Click the link again, nothing. 再次单击链接,什么也没有。 Overload the page, the link works, etc. What is wrong in the script, why it triggered only once? 重载页面,链接有效等。脚本中有什么问题,为什么仅触发一次?

<script>
    $(function() {
        $('a').click(function() {
            $.get('ajax', function(data) {
                $('#mydiv').html(data);
            });
        });
    });
</script>

<div id="mydiv">
    <a href="#">Update the div!</a>     
</div>

Compared the data in the "mydiv" before and after clicking the link: before clicking the link 在单击链接之前和之后比较“​​ mydiv”中的数据: 单击链接之前

<div id="mydiv">
    <a href="#">
        Update the div!
    </a>
</div>

after link was cliked 链接被点赞后

<div id="mydiv">
    <a href="#">
            Update the div!
            <!--Here is the data that came from.-->
    </a>
</div>

Because you're overwriting the a tag that you attached the click event to, you'd need to rerun the code that attaches the click event again. 因为您要覆盖附加了click事件a标签,所以您需要重新运行附加click事件的代码。 Or you could use event delegation like blex suggests: 或者您可以使用blex建议的事件委托:

$(document).on("click", "a", function(){

}

由于是动态创建a您应该使用:

$(document).on("click", "a", function() {

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

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