javascript - 追加后jquery 1.7点击事件不起作用

标签 javascript jquery events onclick

我正在研究来自 http://learn.jquery.com/events/event-delegation/ 的事件委托(delegate) .我有以下代码:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <meta name="description" content="A small web app to manage todos">
        <title>TO-DO jQuery Tests</title>

    <!--src attribute in the <script> element must point to a copy of jQuery -->
    <script type="text/javascript" src="http://code.jquery.com/jquery-2.0.3.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $( "article" ).on( "click","a", function() {
                console.log( "The ID attribute of the link is: " + $(this).attr('id'));
            });
            //The .append()method inserts the specified content as the last child of each element in the jQuery collection -->
            $( "#test-container" ).append("<article> <a href=\"#\"id='link-2'>Link 2</a> </article>" );
        });
    </script>
</head>
<body>
    <div id="test-container">
        <article>
            <a href="#" id="link-1">Link 1</a>
        </article>
    </div>
</body>

当我点击 Link2 时,控制台上没有输出?为什么事件处理不起作用?

最佳答案

你必须绑定(bind)到最近的静态父级。
本例 test-container.

$( "#test-container" ).on( "click","article a", function() {
    // your code
});

关于javascript - 追加后jquery 1.7点击事件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20640620/

相关文章:

javascript - 我如何避免在 JavaScript 中首先使用 parseFloat/Int, number()?

javascript - react native - react-native-maps initialRegion 不起作用

php - 随机放置图像,不重叠

c - 用cudaEvent_t测CPU时间靠谱吗?

javascript - Twitter API - 如果超出速率限制

javascript - 如何使 Vuex 存储更改触发渲染刷新?

javascript - 为什么wavesurferjs 会溢出父div

javascript - 如何防止在 iframe 中浏览时打开新选项卡或窗口

JavaScript 窗口按比例调整大小

javascript - 如何为其他元素后面的元素触发 onMouseEnter