在javascript中实现角度ng-repeat特征 [英] achieving angular ng-repeat like feature in javascript

查看:83
本文介绍了在javascript中实现角度ng-repeat特征的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一种代码来实现像角度的ng-repeat。基本上是html中的for循环。
代码使用类循环获取每个元素,并使用通过info属性给出的信息对其进行处理。以下是代码:
HTML

Im currently working on a code to achieve something like ng-repeat in angular. Basically a for-loop in html. the code takes every element with the class "loop" and processes it with the information given through the "info" attribute. Here is the code : HTML

<div class="loop" data-info="i in 1 to 10">
 -i-
</div>

Javascript

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);
}); 

现在我还包括用数字替换 - 变量的功能。

Now i have also included the feature to replace the - variable - with the numbers.

一切都很完美,但是当循环嵌套时,即

Everything worked perfectly but when the loops are nested i.e

<div class="loop" data-info="i in 1 to 10">
 <div class="loop" data-info="j in 1 to 10">
  -j-
 </div>
</div>

它在嵌套循环上不起作用,即-j-不会被数字取代。
我不知道为什么会这样,感谢任何帮助。

it doesnt work on the nested loop ,i.e -j- doesnt get replaced with the numbers. I dont know why this is happening ,any help is appreciated.

推荐答案

替换失败,因为HTML已更改,以及jQuery为 for 循环收集的下一个 .loop 引用,不再代表之前的内容。

The replacement fails because the HTML is changed, and the next .loop reference that jQuery had collected for your for loop, no longer represents what it was before.

相反,让你的 for 循环反方向:

Instead, make your for loop go in reversed direction:

$($(".loop").get().reverse()).each(function(i){
    // etc...

代码段:

$($(".loop").get().reverse()).each(function(i){
  var loop_info=$(this).attr("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);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="loop" info="i in 1 to 10">
    <div class="loop" info="j in 1 to 10">
      -i-:-j-
    </div>
</div>

这篇关于在javascript中实现角度ng-repeat特征的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆