I’m learning jQuery/javascript and have a rather basic question. Why doesn’t this work? Thanks in advance.
<script type="text/javascript">
$(document).ready(function () {
$('<div/>', {
id: 'foo',
text: 'Does not work'
}).appendTo('body'); });
</script>
<script type="text/javascript">
$("#foo").click(function () {
alert('Success'); });
</script>
It doesn’t work because the second script section will execute before
$(document).readyis fired. Thus it will be trying to attach the onclick handler to an element that doesn’t exist yet.You can make it work by either attaching the
click()event to the element as you add it:or by using
on():