简体   繁体   中英

jQuery click function not working on appended button

I have this.append function which generates a button for every element:

.append('<button type="button" id="add">Hinzufügen</button>')

Then i have this function which should do something when I click on the button above. The function works on a button which is not "appended".

$(document).ready(function () {
   $("#add").on("click", function () {
      alert("Test");
    });   
});

Does anyone know, why this doesn't work?

A page can't be manipulated safely until the document is ready. jQuery detects this state of readiness and allows you to use ready() . The code included inside $( document ).ready() will only run once the Document Object Model (DOM) is ready for JavaScript code to execute.

You are probably appending the button after this code is being executed.

Another issue you should probably fix is making the id's attributes unique.

More about ready() here

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