簡體   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