我正在使用ajax获取用户数据列表。但是在这个ajax调用之后,我必须向每个用户呈现一个包含许多用户数据的html结构(类似于数据表)。我的疑问是如何以一种实用而优雅的方式“存储”HTML代码,以保持代码的可读性,并允许我插入用户数据。
用组件模板创建一个文件并通过javascript包含它是最好的主意吗?如果是,我该怎么做呢?如果不是,什么是最好的?
我所拥有的:
Ajax调用:
`
$("#list-users").click(function(ev){
ev.preventDefault();
$.ajax({
url : '/ajax/Users.php',
type : 'POST',
dataType: 'json',
data : data,
success : function(users){
users.forEach((user, index) => {
//The problem is here. I'm looking for a way to
//"store" the html component code to dont need put
//the code inside a variable.
var complexHtml = '...<p>' + user.name + '</p>...';
$('.list').append(complexHtml);
})
})
})
`
发布于 2019-01-04 11:05:06
使用Vue/React/Angular可以是一个简单的解决方案,因为它们会自动为您完成渲染工作。在不使用这些框架的情况下,我通常会执行以下操作:
示例代码如下:
<div id="target"></div>
<div class="template-code" style="display:none">
<div class="container">
<div class="cls1"></div>
<div class="cls2"></div>
</div>
</div>
<script>
.... ajax success function (){
var div = $(".template-code .container").clone();
$(div).find(".cls1").html("data from ajax result");
$(div).find(".cls2").html("data from ajax result");
.... bind event as well if required ...
$("#target").empty();
$(div).appendTo("#target");
}
</script>
希望这能对你有所帮助。
https://stackoverflow.com/questions/54011265
复制相似问题