Reputation: 3344
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>
Upvotes: 1
Views: 3211
Reputation: 4085
You are binding 2 click events, the first:
$(document.body).click(function () {
... triggers when the body is clicked and responds by binding new click events to the list items, hence the 2nd click response.
It's not clear what you're trying to do, but that code almost certainly isn't it. :)
Upvotes: 0
Reputation: 23250
Well you're adding a click to the document, and when the document is clicked it adds the click events to the list elements. You need to get rid of the first click and change the function to a document ready:
$(document).ready(function() {
$("li").click(function() {
// do something
});
});
Also there's no need for that each loop as you can just bind to the li
element.
Upvotes: 0
Reputation: 26150
It appears you're asking for the body to be clicked before the li's get the click event bound. Further, there's a mix of jQuery and standard javascript, however I'm not addressing that here - just getting it working here:
<script>
$(function () {
$("li").each(function (i) {
this.onclick = function() { alert(i+1); }
});
});
</script>
Note that this will wait until the body loads before running, to ensure every li is displayed and gets the event bound.
Upvotes: 0
Reputation: 34158
$("li").click(function () {
var i = $('li').index(this);
alert(i+1);
});
OR (uses 1.7.1 version) if the li are inserted after page is loaded.
$(document.body).on('click','li',function () {
var i = $('li').index(this);
alert(i+1);
});
Example in action: http://jsfiddle.net/MarkSchultheiss/37D5w/
Upvotes: 0
Reputation: 12806
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.
Upvotes: 2
Reputation: 150253
Just bind the event when the DOM is ready, not after click on the body
:
$(function(){
$("li").each(function (i) {
this.onclick = function() { alert(i+1); }
});
});
Upvotes: 0
Reputation: 2125
It's because the click event on the list items is bound when the DOM is first clicked. I think that what you mean to do, is to bind the click event when the DOM is ready:
$(document).ready(function () {
$("li").each(function (i) {
this.onclick = function() { alert(i+1); }
});
});
Upvotes: 0