简体   繁体   中英

After adding a new element in the DOM, the element does not recognize old script

I have a problem.After adding a new element in the DOM, the element does not recognize old script and the same function that was in this document, how to solve this problem? how to reload the script

<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<div id='content'>Content.....</div>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
<script src='js/script.js' type='text/javascript'></script>
</body>
</html>




//          script.js         //

$('#content').click(function(){
    $('body').append('<div id="apended">Click me!</div>');
});


$('#apended').click(function(){
    alert('click!');
});

When you use .on('click', function (e) {}) function, it works only for existing elements. To handle click event on all selector elements, even for elements which will be added in future, you can use one of these functions:

$(document).on('click', "#appended", function (e) {
    // some code code
    alert('click!');
});

or:

$("body").delegate("#appended", "click", function () {
    // your code goes here
    alert('click!');
});

For more information read article about Understanding Event Delegation

Instead of click function You can use :

  1.live(old version)

  2.delegate

  3.on

But , if you want to use click with immutation of delegate function :

var myFn=function(e){
 if(e.target.id=='apended'){
        alert('click');
   }

}

$(document).click(myFn)

Demo : http://jsfiddle.net/abdennour/7cyjV/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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