javascript - Passing a reference to an element without assigning an id -


i several elements use same onclick handler, have:

function close_div() {     $(this).remove(); }  <div class="closex" onclick="close_div()">the first div</div> <div class="closex" onclick="close_div()"the second div</div> <div class="closex" onclick="close_div()"the third div</div> 

so when click div gets removed dom.

the problem code above onclick doesn't pass useful keyword close_div() can't use it. if gave each div.closex different id pass close_div(id) , $("#"+id).remove(). seems there should way automatically pass reference element clicked, without assigning id element , passing that. missing something?

thanks

even better -- don't use inline handlers.

$('.closex').on('click', function(e){   $(this).remove(); }); 

i'm guessing you're creating these elements dynamically, why you're wanting use inline handlers - still have better solution in separating behaviour , content.
it's called delegation.

basically, if you're going adding these elements dynamically, have static ancestor within dom somewhere - , key attach handler that.

for example:

$('#ancestor-container').on('click', '.closex', function(e){   $(this).remove(); }); 

Comments

Popular posts from this blog

Why does Ruby on Rails generate add a blank line to the end of a file? -

keyboard - Smiles and long press feature in Android -

node.js - Bad Request - node js ajax post -