【问题标题】:achieving angular ng-repeat like feature in javascript在 javascript 中实现类似 Angular ng-repeat 的功能
【发布时间】:2016-11-20 04:31:47
【问题描述】:

我目前正在编写代码以实现 ng-repeat 之类的 Angular。基本上是html中的for循环。 该代码采用“循环”类的每个元素,并使用通过“信息”属性提供的信息对其进行处理。这是代码: HTML

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

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

现在我还加入了将 - 变量 - 替换为数字的功能。

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

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

它不适用于嵌套循环,即 -j- 不会被数字替换。 我不知道为什么会这样,感谢任何帮助。

【问题讨论】:

  • info 是无效属性。不要再犯同样的错误,改用data-info
  • @Roko 感谢您指出错误,我将立即编辑问题
  • 因此,嵌套循环,内部循环在一个i 中运行j 次。所以基本上你应该首先检查任何data-info 元素是否有其他data-info 子元素并采取相应的行动。 $(this).html(printed); 将在第一次 .each() 的元素迭代时销毁子内容。表示内部 .loop 已被销毁/替换,此时无法在 DOM 缓存中访问。
  • @Roko 那么有没有办法从孩子而不是父母开始循环?或者有没有办法检查循环的子或孙子是否包含循环类?

标签: javascript jquery angularjs-ng-repeat


【解决方案1】:

替换失败,因为 HTML 已更改,并且 jQuery 为您的 for 循环收集的下一个 .loop 引用不再代表它之前的样子。

相反,让您的 for 循环反向:

$($(".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>

【讨论】:

  • 非常简单的解决方案
猜你喜欢
  • 2018-05-26
  • 2018-10-08
  • 1970-01-01
  • 2014-11-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多