繁体   English   中英

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

[英]how to get event on dynamically added html button

我发布的程序,我正在使用添加按钮添加更多按钮。 但是当我点击添加了按钮值的按钮时,没有发生任何事件。

<?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'的按钮有值,而不是我无法得到结果,即警报。

您需要将事件委托给父项,以便动态添加元素。

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

委托事件 have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers. have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.

您需要在此处使用事件委派,但请确保该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');
    });
});

演示: 小提琴

问题是,当您尝试向其添加单击处理程序时,您的元素不存在。 只需移动$('#hh').on('click'...$('.input').click的匿名函数内$('.input').click

        $('.input').click(function()
        {
            $("p").prepend('<input type="button" id="hh" value="remmove" />');
            $('#hh').on('click',function()
            {
               alert('raman');
            });
        });

您也可以使用链接方法

$(document).ready(function() {
  $('.input').click(function() {
    $("p").prepend('<input type="button" id="hh" value="remmove" />').find("#hh").on('click',function() {
      alert('raman');
    });
  });
});

你应该用这个

  $(document).ready(function () {
      $('.input').click(function () {
          $("p").prepend('<input type="button" id="hh" value="remmove" />');
      });
      $(document).on('click', "#hh", function () {
          alert('raman');
      });

  });

http://jsfiddle.net/AZdEy/

暂无
暂无

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

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