猿问

如何在循环中或为每个数组元素使用 .clone()?

出于某种原因,我必须修改用于创建发票的软件模板。发票是在 html 中生成的,因此,我认为我可以用 Stylish 和 Grease Monkey 来做到这一点(没有开发人员的支持,所以我必须自己做)。基本上我有一些没有 id 的 div 元素和表格。我为每个元素生成了唯一的 id(这部分代码有效),我现在需要的是克隆 "#order-"+index+"-details" 并将其添加到 "#order"+index+"lines" 前面,其中 index of " #order-"+index+"-details" 匹配 "#order"+index+"lines"(这部分不匹配)。我知道代码是业余的和丑陋的,但它不一定是高效的——它必须有效;)。


var orders=document.querySelectorAll("div.pages");

    for(var i = 0; i < orders.length; i++){


$("body").find("div.pages").each(function(index){

$(this).attr("id","order-"+index+"-page");

})


$("body").find("div.pages > div:nth-child(1) > table:nth- 

child(3)").each(function(index){

$(this).attr("id","order-"+index+"-details");

})


$("body").find("div.pages > div:nth-child(1) > table:nth- 

child(7)").each(function(index){

$(this).attr("id","order-"+index+"-lines");

})


$order_details = $("#order-"+index+"-details").clone();

$("#order"+index+"lines").prepend($order_details);


}

这部分不起作用


$order_details = $("#order-"+index+"-details").clone();

$("#order-"+index+"-lines").prepend($order_details);

当我尝试时它有效:


$order_details = $("#order-1-details").clone();

$("#order-1-lines").prepend($order_details);


$order_details = $("#order-2-details").clone();

$("#order-2-lines").prepend($order_details);

但我需要循环它。非常感谢您的所有建议。


紫衣仙女
浏览 129回答 1
1回答

呼如林

$order_details = $("#order-"+index+"-details").clone();$("#order"+index+"lines").prepend($order_details);应该$order_details = $("#order-"+i+"-details").clone();$("#order"+i+"lines").prepend($order_details);如果代码格式化就更清楚了:var orders = document.querySelectorAll("div.pages");for (var i = 0; i < orders.length; i++) {&nbsp; &nbsp; $("body").find("div.pages").each(function(index) {&nbsp; &nbsp; &nbsp; &nbsp; $(this).attr("id","order-"+index+"-page");&nbsp; &nbsp; });&nbsp; &nbsp; $("body").find("div.pages > div:nth-child(1) > table:nth-&nbsp;&nbsp; &nbsp; child(3)").each(function(index){&nbsp; &nbsp; &nbsp; &nbsp; $(this).attr("id","order-"+index+"-details");&nbsp; &nbsp; });&nbsp; &nbsp; $("body").find("div.pages > div:nth-child(1) > table:nth-&nbsp;&nbsp; &nbsp; child(7)").each(function(index){&nbsp; &nbsp; &nbsp; &nbsp; $(this).attr("id","order-"+index+"-lines");&nbsp; &nbsp; });&nbsp; &nbsp; $order_details = $("#order-"+i+"-details").clone();&nbsp; &nbsp; $("#order"+i+"lines").prepend($order_details);}
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答