Reputation: 11215
it's supposed to add a number to the right of the LI, so the first LI would prepend the number 1, the second LI would prepend 2, etc.
also, are i = i+1;
and i++;
the same? if not, what's the difference?
http://jsfiddle.net/nicktheandroid/U8byW/9/
Upvotes: -1
Views: 107
Reputation: 1039548
You have some very broken and messed up simple and double quotes in your code, not to mention that you are trying to modify the i
variable over which you are looping which is not a good thing. Try like this:
$('li').each(function (index) {
$(this).append(
$('<span/>').addClass('commentnumber').text('#' + (index + 1))
);
});
or if you prefer (but be careful with the simple and double quotes):
$('li').each(function (index) {
$(this).append('<span class="commentnumber">#' + (index + 1) + '</span>');
});
And demo here.
Upvotes: 2
Reputation: 19419
Try this solution: http://jsfiddle.net/U8byW/10/
The problems you had with yours were:
class="commentnumber"
, you were breaking the JS strings, causing an error (Uncaught SyntaxError: Unexpected identifier
)i
at all: jQuery handles that for you. But to answer your question, i = i + 1
and i++
are roughly the same thing, yes. The difference is that i = i + 1
returns the new value (with 1 added to it) while i++
returns the old value and then increments it by one. You can also use i += 1
or ++i
. All of those are rough equivalents.+
) is the same as the addition operator (+
), unlike some languages (e.g., PHP, where concatenation is .
instead).Hope this helps.
Edit: I realized why you were incrementing i
: to have the lines start at 1 instead of 0. Ignore me saying you don't need to increment it. I wasn't thinking straight.
Upvotes: 1
Reputation: 499392
This line is the problem:
$(this).append("<span class="commentnumber"> #' i '</span>");
Use this instead:
$(this).append("<span class='commentnumber'> #" + i + "</span>");
Note that the string delimiters now match and the use of + to concatenate the strings.
When updating your code, it works - http://jsfiddle.net/U8byW/14/
And yes, i = i + 1;
is the same as i++
for a single line statement.
Upvotes: 3