我目前正在研究一种代码来实现像角度的ng-repeat.基本上是html中的for循环.代码使用类"循环"获取每个元素,并使用通过"info"属性给出的信息对其进行处理.这是代码:HTML
<div class="loop" data-info="i in 1 to 10">
-i-
</div>
Run Code Online (Sandbox Code Playgroud)
使用Javascript
$(".loop").each(function(i){
var loop_info=$(this).attr("data-info");
var fin=loop_info.match(/(.*) in (\d+) to (\d+)/);
var variable=fin[1],
initial=fin[2],
final=fin[3];
var htm=$(this).html(),printed="";
for(j=initial;j<=final;j++){
var temp=htm;
var r=new RegExp("-("+variable+")-","g")
temp=temp.replace(r,j);
printed+=temp;
}
$(this).html(printed);
});
Run Code Online (Sandbox Code Playgroud)
现在我还包括用数字替换 - 变量的功能.
一切都很完美,但是当循环嵌套时,即
<div class="loop" data-info="i in 1 to 10">
<div class="loop" data-info="j in 1 to 10">
-j-
</div>
</div>
Run Code Online (Sandbox Code Playgroud)
它不适用于嵌套循环,即-j-不会被数字替换.我不知道为什么会这样,任何帮助都表示赞赏.