javascript - How to handle after-generated buttons with jQuery? -


i've created buttons javascript, i've added these html. want handle these jquery. how worked click on b_1 , b_2?

$("#mainbutton").click(function (){    document.getelementbyid("content").innerhtml = '<button id="b_1">button1</button><button id="b_2">button2</button>'  })  $("#b_1").click(function (){    alert("you've clicked button1!");  })    $("#b_2").click(function (){    alert("you've clicked button2!");  })
<head>  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  <button id="mainbutton">click me!</button>  <div id="content"></div>  </head>

you need attach event body , select element in second argument :)

edit: i've used body, it's better practice use closest parent static on page.

$("#mainbutton").click(function (){    document.getelementbyid("content").innerhtml = '<button id="b_1">button1</button><button id="b_2">button2</button>'  })  $("body").on('click','#b_1',function (){    alert("you've clicked button1!");  })    $("body").on('click', '#b_2', function (){    alert("you've clicked button2!");  })
<head>  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>  <button id="mainbutton">click me!</button>  <div id="content"></div>  </head>


Comments

Popular posts from this blog

Is there a better way to structure post methods in Class Based Views -

performance - Why is XCHG reg, reg a 3 micro-op instruction on modern Intel architectures? -

jquery - Responsive Navbar with Sub Navbar -