使用while循环重复jquery语句

Repeat jquery statement using while loop

本文关键字:jquery 语句 while 循环 使用      更新时间:2023-09-26

我是JavaScript/jQuery的新手。我有一个链接到页面的脚本文件。我试图在文件中使用while循环重复一个简单的jQuery语句。以下是代码示例。如何在while循环中重复它们?

代码:

e(".rwpt_testimonials .rwpt_quotes ul li:nth-child(1)").addClass("quote_1");
e(".rwpt_testimonials .rwpt_quotes ul li:nth-child(2)").addClass("quote_2");
e(".rwpt_testimonials .rwpt_quotes ul li:nth-child(3)").addClass("quote_3");
e(".rwpt_testimonials .rwpt_quotes ul li:nth-child(4)").addClass("quote_4");
e(".rwpt_testimonials .rwpt_quotes ul li:nth-child(5)").addClass("quote_5");
e(".rwpt_testimonials .rwpt_quotes ul li:nth-child(6)").addClass("quote_6");
e(".rwpt_testimonials .rwpt_quotes ul li:nth-child(7)").addClass("quote_7");
e(".rwpt_testimonials .rwpt_quotes ul li:nth-child(8)").addClass("quote_8");
e(".rwpt_testimonials .rwpt_quotes ul li:nth-child(9)").addClass("quote_9");
e(".rwpt_testimonials .rwpt_quotes ul li:nth-child(10)").addClass("quote_10");

我正在尝试但没有工作:

var i = 0;
while( i < 10 ) {
return 'e(".rwpt_testimonials .rwpt_photos ul li:nth-child(' + i + ')").addClass("quote_' + i + '");';
  i++;
}

您可以使用jQuery方法.each()来遍历每个列表项。

JS(jQuery):

$('.rwpt_testimonials .rwpt_quotes ul li').each(function(i) {
    $(this).addClass('quote_'+(i+1));
});

这是一把小提琴。

return仅用于返回值的函数中。在这里,您可以直接执行e:

var i = 0;
while( i < 10 ) {
    e(".rwpt_testimonials .rwpt_photos ul li:nth-child(" + i + ")").addClass("quote_" + i);
    i++;
}

然而,当你知道要循环多少次时,通常会使用for循环(而不是while):

for(var i = 0; i < 10; ++i) {
    e(".rwpt_testimonials .rwpt_photos ul li:nth-child(" + i + ")").addClass("quote_" + i);
}

不过,为了效率和可维护性,您可能需要重新思考您正在做什么。