i’m trying to bind a click event to some div that has a id="unit". Theses div are generate in run-time and my javascript doesn’t seems to work.
my javascript click event.
$("#unit").click(function(){
alert('1');
});
before ajax call.
<div id="content">
<div id="building">
</div>
<div id="units">
</div>
</div>
after ajax call.
<div id="content">
<div id="building">
<div value="1" class="buildingBlock"><h3 style="text-align: center;">Level - 1</h3></div>
<div value="2" class="buildingBlock"><h3 style="text-align: center;">Level - 2</h3></div>
<div value="3" class="buildingBlock"><h3 style="text-align: center;">Level - 3</h3></div>
<div value="4" class="buildingBlock"><h3 style="text-align: center;">Level - 4</h3></div>
</div>
<div id="units">
<div value="1" id="unit">#02-01<br>3 room(s)</div>
<div value="2" id="unit">#02-02<br>2 room(s)</div>
<div value="3" id="unit">#02-03<br>5 room(s)</div>
</div>
</div>
Because you are dynamically appending the
#unitelements, you need to delegate the event to the nearest parent element. Try this:Also, multiple
idattrbutes are invalid. You should change the code to use classes, like this: