Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

javascript - refresh DOM after append element

<!doctype html>
<html>

<head>
  <title>test</title>
  <meta charset="UTF-8">
  <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
  <script>
    $(document).ready(function() {
      $('#main_body').append("<h1>Hello</h1><input id="but" type="button">Click");
      $("#but").on("click", function() {
        alert("bla bla");
      });
    });
  </script>
</head>

<body id="main_body"></body>

</html>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

For dynamically added elements you need event delegation, use the other version on jQuery on(), you can delegate event to static parent of the dynamically added elements. In your case you can use #main_body

$('#main_body').on( "click", "#but", function() {
    alert( "bla bla" );
});    

Delegated events 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, jQuery Docs

Your code works here as it is because you are adding the dynamically element before binding the event but using event delegation will free you from the sequence you use to add the dynamic elements.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...