jQuery function not binding to newly added dom ele

2019-01-03 23:41发布

Here's index.html:

<head>
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.2/jquery.min.js"></script>
  <script type="text/javascript">

    $(document).ready(function() {
      $('.btn_test').click(function() { alert('test'); });
    });

    function add(){
      $('body').append('<a href=\'javascript:;\' class=\'btn_test\'>test</a>');
    }

  </script>
</head>
<body>
  <a href="javascript:;" class="btn_test">test1</a>
  <a href="javascript:;" onclick="add()">add</a>
</body>

If I click on test1 link, it shows alert('test'), but if I click on add link then click on test, it doesn't show anything.

Could you explain it?

13条回答
走好不送
2楼-- · 2019-01-04 00:02

Because the event is tied to each matching element in the document ready. Any new elements added do NOT automatically have the same events tied to them.

You will have to manually bind the event to any new element, after it is added, or use the live listener.

查看更多
虎瘦雄心在
3楼-- · 2019-01-04 00:03

This is because you click event is only bound to the existing element at the time of binding. You need to use live or delegate which will bind the event to existing and future elements on the page.

$('.btn_test').live("click", function() { alert('test'); });

Jquery Live

查看更多
太酷不给撩
4楼-- · 2019-01-04 00:04

.click binds to what is presently visible to jQuery. You need to use .live:

$('.btn_test').live('click', function() { alert('test'); });
查看更多
Animai°情兽
5楼-- · 2019-01-04 00:06

When the document loads you add event listeners to each matching class to listen for the click event on those elements. The same listener is not automatically added to elements that you add to the Dom later.

查看更多
家丑人穷心不美
6楼-- · 2019-01-04 00:06

After jquery 1.7 on method can be used and it really works nice

<!DOCTYPE html>
<html>
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js">
    </script>
<script>
    $(document).ready(function(){
      $("p").on("click",function(){
       alert("The paragraph was clicked.");
       $("body").append("<p id='new'>Now click on this paragraph</p>");
    });
    $(document).on("click","#new",function(){
       alert("On really works.");
      });
    });
</script>
</head>
<body>
    <p>Click this paragraph.</p>
</body>
</html>

see it in action http://jsfiddle.net/rahulchaturvedie/CzR6n/

查看更多
Juvenile、少年°
7楼-- · 2019-01-04 00:08

You need to add a proper button click function to give a proper result

$("#btn1").live(function() { alert("test"); });
查看更多
登录 后发表回答