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条回答
Summer. ? 凉城
2楼-- · 2019-01-04 00:11

I have same problem like question I was just near to pulling my hair then i got the solution. I was using different syntax

$(".innerImage").on("click", function(){ 
alert("test");
});

it was not working for me (innerImage is dynamically created dom) Now I'm using

$(document).on('click', '.innerImage', function() { alert('test'); });

http://jsfiddle.net/SDJEp/2/

thanks @Moshe Katz

查看更多
登录 后发表回答