Home > Back-end >  onclick function in html set by updating innerHTML not working
onclick function in html set by updating innerHTML not working

Time:09-24

I have a JS function called buyAnimal(id) that works as expected if I set my index.html to include

<div onclick="buyAnimal(0)"></div> it works properly, but if I use

let html = `<div onclick="buyAnimal(0)"></div>`
$('#element').html(html);

The onclick functionality does not come through, is this normal or do I have to specifically attach an onclick function to that element with my JS?

CodePudding user response:

You should attach event handle to dynamic div by this

$(document).on("click", '.buy', function() {
    buyAnimal(0);
});

let html = `<div class='buy'>BUY</div>`
$('#element').html(html);
$(document).on("click", '.buy', function() {
    buyAnimal(0);
});

function buyAnimal(n){
   console.log('buy...'   n);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="element"></div>

CodePudding user response:

do I have to specifically attach an onclick function to that element with my JS?

You don't need to do that. You can check the below demo.

let html = `<div onclick="buyAnimal(0)">buyAnimal</div>`
$('#element').html(html);

function buyAnimal(id) {
  console.log('buyAnimal', id);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="element"></div>

  • Related