单击元素时出现问题,这些元素是用.html()添加到页面的

Issue with clicking elements, that were added to page with .html()

本文关键字:元素 html 添加 问题 单击      更新时间:2024-04-28

所以,我在点击元素上的事件时遇到了问题,这些事件是由jQuery的.html()函数呈现的。这是我正在测试的代码:

<html>
<head>
    <title>Test</title>
    <script type="text/javascript" src="static/jquery-2.0.3.min.js"></script>
</head>
<body>
    <div id="content">
        <input type="submit" name="loginButton" id="loginButtonID"/>
    </div>
    <script>
        $('#loginButtonID').click(function() {
            $('#content').html('<button name="loginButton" id="newPasswordID">New Button</button>')
        });
        $('#newPasswordID').on('click', function() {
            alert("alert");
        });
    </script>
</body>
</html>

正如您所看到的,在一开始,我使用id="loginButtonID"渲染了一个按钮。我有一个.click()事件,它通过.html()(因为.text()将只返回该按钮的HTML代码)和id="newPasswordID"创建另一个按钮,对于该按钮,我有另一个事件.on()(而不是.click()),但该事件不起作用。所以问题是:如何使.on()事件为第二个按钮工作?

谢谢。

问题是,当您尝试挂接事件时,#newPasswordID元素不存在。因此,当您执行$("#newPasswordID")时,它与任何内容都不匹配,因此不会设置任何处理程序。

您可以在呈现该元素后执行此操作,也可以将事件挂接到元素所在的某个容器上(看起来像#content)并使用事件委派:

$("#content").on("click", "#newPasswordID", function() {
    // ...
});

由于这确实将click挂接在#content上,但只有当事件经过与#newPasswordID匹配的元素时才会触发它,因此挂接事件时#newPasswordID是否存在并不重要。

试试这个:

$('#content').html(
    $('<button />').attr('name',"loginButton")
        .attr('id', "newPasswordID")
        .click(function() {
            alert('alert');
        })
);