I have a large ordered list and am using jquery to add an onclick handler to each line. This works well after the first click, but on the first click following the page load, nothing happens at all. There are no javascript errors on the page. Any suggestions please?
<ol>
<li>Line 1</li>
<li>Line 2</li>
<li>Line 3</li>
</ol>
<script>
$(document.body).click(function () {
$("li").each(function (i) {
this.onclick = function() { alert(i+1); }
});
});
</script>
The problem is that you wrapped it in
$(document.body).click
so the inner code will not be executed unless you click somewhere in the page first.Try without the
$(document.body).click
, should work fine.