jQuery 使用each() 循环遍历类 - 问题
我使用此代码循环遍历每个“.accessoryrow”,然后选择“dialog”+ counter 和“.see-details”+ counter。因此,第一次循环时,它选择dialog1类和see-details1类;第二次dialog2、see-details2等等。我认为我没有正确地向选择器添加计数器。请纠正我。谢谢
代码:
var counter = 1;
$(function () {
$(".accessoryrow").each(function() {
$(".dialog" + counter).dialog({
autoOpen: false,
show: "blind",
hide: "fade"
});
$(".see-details" + counter).click(function () {
$(".dialog" + counter).dialog("open");
return false;
});
counter++;
});
I am using this code to loop through each ".accessoryrow" and then select "dialog" + counter and ".see-details" + counter. So first time when loop goes by it selects dialog1 class and see-details1 class; second time dialog2, see-details2 and so on. I think I am not correctly adding counter to the selector. Please correct me. Thank you
CODE:
var counter = 1;
$(function () {
$(".accessoryrow").each(function() {
$(".dialog" + counter).dialog({
autoOpen: false,
show: "blind",
hide: "fade"
});
$(".see-details" + counter).click(function () {
$(".dialog" + counter).dialog("open");
return false;
});
counter++;
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题是,在单击链接之前,不会评估
$(".dialog" + counter).dialog("open");
行。因此,它使用的是counter
的值,该值是当时的当前值。更好的方法是完全删除计数器,并使用 jQuery 选择器来选择正确的 .dialog。如果没有 HTML,我无法说出它应该是什么样子,但您会希望单击功能看起来像
当然,假设 .dialog 元素实际上是 .see 的同级元素-细节。如果不是,您需要多遍历一下树。
The problem is that the
$(".dialog" + counter).dialog("open");
line isn't getting evaluated until the link is clicked. Thus it's using the value ofcounter
which is current as of then. A better way to do it would be to take out the counter altogether, and use jQuery selectors to select the correct .dialog.Without the HTML, I can't say what it should look like, but you're going to want the click function to look like something along the lines of
Of course, that assumes that the .dialog element is actually a sibling of .see-details. You'll need to traverse the tree a bit more if it isn't.
试试这个(未经测试):
Index 将循环编号传递给函数。它从 0 开始,我认为你需要它从 1 开始,所以我在每个使用它的地方添加了 1。
Try this (untested):
Index passes the loop number to the function. It starts from 0, where I think you need it to start at 1, so I've added 1 to each where it's used.