Why I can’t edit color with append div.
Click button and add new div call ‘block2’,if using $(this), it will not work.
How to fix it ?
HTML
<div id="btn"><input name="click" type="button" value="Click" /></div>
<div class="block1" style=" width:100px; height:100px; background:orange;">I am Block1</div>
JS
$('#btn').click(function(){
var $newDiv=$('<div class="block2" style=" width:100px; height:100px; background:green;">I am Block2</div>');
$( "#btn").parent().append($newDiv);
});
$('.block1').click(function(){
$(this).css('background', 'blue');
});
$('.block2').click(function(){
$(this).css('background', 'blue');
});
Working demo http://jsfiddle.net/e7Apx/
Please note you are appending the element hence use API
.onfor the class.block2:$(document).on('click','.block2',function() { ... });API:
.ondocumentation -> http://api.jquery.com/on/Hope it fits the cause
:)code