I’ve a simple code as following:
<html>
<body>
<div id="div1">
<input class="input1" type="text" value="click me 1" />
</div>
<script type="text/javascript">
$('.input1').click( function() { alert('clicked'); });
$('#div1').append('<input class="input1" type="text" value="click me 2" />');
</script>
</body>
</html>
I found that the 2nd textbox, which was appended to the “#div1”, didn’t get the click respond which is associated to the class “input1”.
what am I missing? please advise me, thank you very much.
You should use event delegation with the
.on()method…This places the handler on
#div1. When clicks happen inside of it, the'.input1'selector is run, and if the element clicked matches, the handler is invoked.Or in older versions of jQuery (pre 1.7), use
.delegate().