[英]How can I make this jQuery function more efficient with looping?
I need to use jQuery to find elements, get their nested paragraph and then add in a div before this paragraph. 我需要使用jQuery查找元素,获取其嵌套段落,然后在该段落之前添加div。 I have it working fine, but it's very repetitive code and I want to make it more efficient and tidy it up, but I'm not sure how.
我的代码工作正常,但是它是重复性很强的代码,我想使其更加高效并整理整齐,但是我不确定如何做。
Here is the code: 这是代码:
$(".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 string outside of the loop div
html字符串带出循环 this
context this
上下文 return
at the end is not necessary return
Code: 码:
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"));
});
You can also shorten your code as follow if you want to iterate over all the elements whose class starts with element
: 如果要遍历类以
element
开头的所有元素,也可以按照以下方式缩短代码:
var div = "<div>Test 1</div>";
$(".container .row [class^=element] p").each(function () {
$(div).insertBefore($(this));
});
I'll also suggest you to use the same class name to all the elements instead of elementX
. 我还建议您对所有元素使用相同的类名,而不要使用
elementX
。
Looks like normal selectors can reduce the load. 看起来普通的选择器可以减少负载。
$(".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.