gpt4 book ai didi

javascript - 在javascript中实现类似angular ng-repeat的功能

转载 作者:数据小太阳 更新时间:2023-10-29 05:11:54 25 4
gpt4 key购买 nike

我目前正在编写代码以实现类似 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- 不会被数字替换。 我不知道为什么会这样,感谢任何帮助。

最佳答案

替换失败是因为 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>

关于javascript - 在javascript中实现类似angular ng-repeat的功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38421941/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com