Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
995 views
in Technique[技术] by (71.8m points)

jquery - achieving angular ng-repeat like feature in javascript

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

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

Instead, make your for loop go in reversed direction:

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

Snippet:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...