简体   繁体   中英

how to add a button as html to a div and add click function

In the following code the button "alt2" shows up but does not alert "hi"

Is this the proper way to add a button?

<body>
<div id="test"></div><br>
<button id="add">add</button><br>
<button id='alt'>alt1</button>
<script type="text/javascript" >
$(function(){
    $("#add").click(function(){
        $("#test").html("<button id='alt2'>alt2</button>");     
    });
    $("#alt").click(function(){
        alert("hi");

    }); 

});

</script>

 $("#add").click(function() { $("#test").html("<button id='alt2'>alt2</button>"); }); $("#alt").click(function() { alert("hi"); }); $(document).on('click',"#alt2",function() { // use .on() alert("hi 2"); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div id="test"></div> <br> <button id="add">add</button> <br> <button id='alt'>alt1</button> 

Use .on() for dynamically added elements.

Description: Attach an event handler function for one or more events to the selected elements.

on("click")... for the second alt2 is missing. also i would suggest you use on("click")... instead of .("click") . .("click") this one may miss to fire the second time

 <body> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script> <div id="test"></div><br> <button id="add">add</button><br> <button id='alt'>alt1</button> <script type="text/javascript" > $(function(){ $(document).on("click", "#add", function(e) { e.preventDefault(); $("#test").html("<button id='alt2'>alt2</button>"); }); $(document).on("click", "#alt", function(e) { e.preventDefault(); alert("hi 1"); }); $(document).on("click", "#alt2", function(e) { e.preventDefault(); alert("hi 2"); }); }); </script> </body> 

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