2014-10-20 105 views
-2

我试图做一个jQuery模板,但我坚持每个jQuery的中间。这里是我的代码:jQuery每个返回相同的结果

var json = [{"threadid":"1","username":"dvsdvs"},{"threadid":"32","username":"rgfedvre"}]; 
var template = '<li id="thread_{threadid}">{username}</li>'; 
jQuery.each(json, function(index, value) { 
    jQuery.each(value, function(subindex, subvalue) { 
    template = template.replace('{' + subindex + '}', value[subindex]); 
    }); 
$(template).appendTo('body'); 
}); 

,但结果总是

<li id="thread_1">dvsdvs</li> 
<li id="thread_1">dvsdvs</li> 

我想获得一些帮助,谢谢。

+0

一般形式是'jQuery(选择器).each(...)'而不是'jQuery.each(selector,...)'。 – ArtOfCode 2014-10-20 21:19:36

+1

您正在第一次循环迭代中替换您的'template'中的'{threadid}'。第二次迭代,它已被替换。 – 2014-10-20 21:19:49

+1

@ArtOfCode:'jQuery(selector).each(...)'仅针对jQuery对象/ DOM元素。 'jQuery.each(selector,...)'在这里是正确的,因为他使用了一个数组。 – 2014-10-20 21:20:35

回答

1

逻辑错误。您在第一遍循环中覆盖原始模板,然后在第二遍时无法找到占位符。只需在每次迭代中重新定义您的模板。

var json = [{"threadid":"1","username":"dvsdvs"},{"threadid":"32","username":"rgfedvre"}]; 
 
jQuery.each(json, function(index, value) { 
 
    var template = '<li id="thread_{threadid}">{username}</li>'; 
 
    jQuery.each(value, function(subindex, subvalue) { 
 
     template = template.replace('{' + subindex + '}', subvalue); 
 
    }); 
 
    $(template).appendTo('body'); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

+0

谢谢!现在它的工作。 – hegbl 2014-10-20 21:25:02

2

要么每次(所以有可用的占位符)开始一个新的模板,或者更换成一个临时变量,和追加的是:

var json = [{"threadid":"1","username":"dvsdvs"},{"threadid":"32","username":"rgfedvre"}]; 
 

 
var template = '<li id="thread_{threadid}">{username}</li>'; 
 

 
jQuery.each(json, function(index, value) { 
 
    var t = template; 
 
    
 
    jQuery.each(value, function(subindex, subvalue) { 
 
    t = t.replace('{' + subindex + '}', value[subindex]); 
 
    }); 
 
    
 
    $(t).appendTo('body'); 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

+0

绝对喜欢这个选项,因为它更适用于在其他地方移动模板。 – 2014-10-20 21:24:05

+0

谢谢!现在它的工作。 – hegbl 2014-10-20 21:24:25

相关问题