[英]How can I make this jQuery function more efficient with looping?
我需要使用jQuery查找元素,获取其嵌套段落,然后在该段落之前添加div。 我的代码工作正常,但是它是重复性很强的代码,我想使其更加高效并整理整齐,但是我不确定如何做。
这是代码:
$(".container .row").each(function(index) {
var row1,
row2,
row3,
row4,
newRow1,
newRow2,
newRow3,
newRow4;
row1 = jQuery(this).find(".elementA");
row2 = jQuery(this).find(".elementB");
row3 = jQuery(this).find(".elementC");
row4 = jQuery(this).find(".elementD");
newRow1 = row1.find("p");
newRow2 = row2.find("p");
newRow3 = row3.find("p");
newRow4 = row4.find("p");
$("<div>Test 1</div>").insertBefore(newRow1);
$("<div>Test 1</div>").insertBefore(newRow2);
$("<div>Test 1</div>").insertBefore(newRow3);
$("<div>Test 1</div>").insertBefore(newRow4);
return;
});
div
html字符串带出循环 this
上下文 return
码:
var div = "<div>Test 1</div>";
$(".container .row").each(function (index) {
var $this = jQuery(this);
$(div).insertBefore($this.find(".elementA p"));
$(div).insertBefore($this.find(".elementB p"));
$(div).insertBefore($this.find(".elementC p"));
$(div).insertBefore($this.find(".elementD p"));
});
如果要遍历类以element
开头的所有元素,也可以按照以下方式缩短代码:
var div = "<div>Test 1</div>";
$(".container .row [class^=element] p").each(function () {
$(div).insertBefore($(this));
});
我还建议您对所有元素使用相同的类名,而不要使用elementX
。
看起来普通的选择器可以减少负载。
$(".container .row").each(function (index) {
var newRow = jQuery(this).find(".elementA p, .elementB p, .elementC p, .elementD p");
$("<div>Test 1</div>").insertBefore(newRow);
return;
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.