[英]jQuery: Why doesn't this little function work?
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. 应该在LI的右边添加一个数字,因此第一个LI会在数字1之前,第二个LI会在数字2之前,依此类推。
also, are i = i+1;
另外, i = i+1;
and i++;
和i++;
the same? 相同? if not, what's the difference? 如果没有,有什么区别?
http://jsfiddle.net/nicktheandroid/U8byW/9/ http://jsfiddle.net/nicktheandroid/U8byW/9/
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/ 更新代码时,它可以正常工作-http://jsfiddle.net/U8byW/14/
And yes, i = i + 1;
是的, i = i + 1;
is the same as i++
for a single line statement. 与单行语句的i++
相同。
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. 您的代码中有一些非常混乱的单引号和双引号,更不用说试图修改循环的i
变量了,这不是一件好事。 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>');
});
Try this solution: http://jsfiddle.net/U8byW/10/ 尝试以下解决方案: 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
) 当您说class="commentnumber"
,您破坏了JS字符串,从而导致错误( Uncaught SyntaxError: Unexpected identifier
) i
at all: jQuery handles that for you. 您根本不需要增加i
:jQuery会为您处理。 But to answer your question, i = i + 1
and i++
are roughly the same thing, yes. 但是要回答您的问题, i = i + 1
和i++
大致相同,是的。 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. 区别在于, i = i + 1
返回新值(添加了1),而i++
返回旧值, 然后将其递增1。 You can also use i += 1
or ++i
. 您也可以使用i += 1
或++i
。 All of those are rough equivalents. 所有这些都是粗略的等价物。 +
) is the same as the addition operator ( +
), unlike some languages (eg, PHP, where concatenation is .
instead). 请注意,字符串连接运算符( +
)与加法运算符( +
)相同,这与某些语言(例如PHP,其中串联为.
)不同。 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
:行从1而不是0开始。忽略我说你不需要递增它。 I wasn't thinking straight. 我不是在想
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.