[英]standard way to generating html for json arrays in jquery
i am trying to generate html for the json returned array of users.. I want to do it the following way but I don't feel this is very effecient way to do this job. 我正在尝试为用户返回的json数组生成html。我想按以下方式进行操作,但我不认为这是完成这项工作的非常有效的方法。 please review the following code and tell me whether i sould use some templated code or is there any standard for this scenario? 请查看以下代码,并告诉我是否愿意使用某些模板代码,或者该场景是否有任何标准?
success: function(e){
console.log(e);
console.log(e.d[0].UserName);
var position2= $("#searchtextbox").position();
$('<div/>',
{
id:'generatedsearchdiv',
css:{
position:'absolute',
left:position2.left,
top:position2.top+20
}
}).appendTo('#searchArea');
for (var i=0; i<=e.d.length; i++)
{
$('<div/>',
{
html:"<span>"+e.d[i].UserName+"<span>"
}).appendTo('#generatedsearchdiv');
}
}
您可以为此使用Jquery模板。
This method is "okay" for small bits of HTML, like <span>{data}</span>
. 对于少量的HTML,例如<span>{data}</span>
,此方法“可以”。 However, if you have much more than that, it really is best for maintainability to use a templating solution. 但是,如果您拥有的不止这些,那么使用模板解决方案对于维护性确实是最好的。 Check out this answer for options. 查看此答案以了解选项。
I have not been sold on the current templating solutions. 目前的模板解决方案尚未售出。 If you aren't either, you can get a quick string formatter if you put this code inline: 如果两者都不是,则可以通过以下代码获得快速的字符串格式化程序:
String.prototype.format = function() {
var pattern = /\{\d+\}/g;
var args = arguments;
return this.replace(pattern, function(capture) {return args[capture.match(/\d+/)]; });
}
You can define formatting strings like so: 您可以像这样定义格式字符串:
var formatHTML = '<span>{0}</span>';
Then use it something like this: 然后使用它像这样:
$('#generatedsearchdiv').append(formatHTML.format(e.d[i].UserName));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.