jquery 函数内的 for 循环
我试图在 jquery 函数中重复一些内容。我尝试了 for 循环,但它似乎不喜欢语法。 例如,我
var number = 2;
现在有一个变量,我
$('tr').html('<td id="'+number+'"></td>');
想要做的就是从 0 循环到数字 (0,1,2) ,这样最终我就会得到 3 。 谢谢
I am trying to repeat something inside a jquery function. I tried a for loop, but it seems it doesnt like the syntax.
for instance i have the variable
var number = 2;
now i have
$('tr').html('<td id="'+number+'"></td>');
what i want to do is loop from 0 to number (0,1,2) so that in the end i end up having 3 .
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
可能有更好的方法,但这应该可行。
这也应该有效(常规 JS):
请注意我如何在 id 前面添加单词“myCell”作为前缀,以确保 XHTML 合规性。 (感谢@Peter Ajtai 指出了这一点)。
编辑
我刚刚注意到另一个问题 - 您正在使用.html函数来添加单元格。但是 .html 会替换匹配元素的整个 html。所以你最终只会得到最后一个单元格。 :)
您可能正在寻找 .append 函数:
编辑 2 - 将双引号移到 myCell 之前而不是之后。
There is probably a better way, but this should work.
This should also work (regular JS):
Note how i prefixed id with the word 'myCell', to ensure XHTML compliancy. (thanks to @Peter Ajtai for pointing that out).
EDIT
I just noticed another problem - you're using the .html function to add the cells. But .html replaces the entire html of the matched element. So you'll only ever end up with the last cell. :)
You're probably looking for the .append function:
EDIT 2 -- moved the double quote before myCell rather than after.
这是使用匿名函数的选项。
Heres an option using an anonymous function.
这对我有用:
This works for me: