php - 如何获取动态添加的 html 按钮上的事件

标签 php javascript jquery html

我发布的程序中我使用添加按钮来添加更多按钮。但是当我单击带有值删除的添加按钮时,不会发生任何事件。

<?php
?>

<html>
<head>
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function()
        {
            $('.input').click(function()
            {
                $("p").prepend('<input type="button" id="hh" value="remmove" />');
            });

            $('#hh').on('click',function()
            {
               alert('raman');
            });
        });


    </script>
</head>
<body>
<p>
    <input type="button" class="input" value="add"/>

</p>
</body>
</html>

请让我知道这段代码有什么问题。当我单击 id 为“hh”且值为 remmove 的按钮时,我无法获得结果,即警报。

最佳答案

您需要在此处使用事件委托(delegate),但请确保 id 在文档中保持唯一。

        $(document).on('click','#hh',function()
        {
           alert('raman');
        })

如果您计划添加多个按钮,请使用类而不是 id

$(document).ready(function() {
    $('.input').click(function() {
        $("p").prepend('<input type="button" class="hh" value="remmove" />');
    });

    $(document).on('click', '.hh', function() {
        alert('raman');
    });
});

演示:Fiddle

关于php - 如何获取动态添加的 html 按钮上的事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17895359/

相关文章:

php - FullText 或 LIKE 搜索问题(无法找到库存)

javascript - 完全展开这个 CSS inline-block div scan-line

javascript - [javascript, jQuery]如何在没有回调的情况下继续另一个动画之前等待动画完全完成

javascript - 在特定于单击元素的超时内更改类

php - 插入数据 php mysql

PHP MVC类根据url决定执行什么方法

php - 多语言 WordPress 网站,提供 2 次安装建议

javascript - 按钮单击事件仅在页面重新加载或功能提醒时起作用

javascript - ExtJS 4 状态提供者

jquery - 如何使用(jQuery 风格)嵌套对象序列化 GET 参数