这是我的HTML。格式化道歉 - 这是我第一个问题!
<div id="Template">
<table cellspacing="0" width="100%">
<tr valign="top">
<td>
<span class="Name" ></span>
(<span class="Id"></span>)
<span class="Addr" ></span><br>
<span class="City" ></span>,
<span class="State" ></span>
<span class="Zip" ></span><br>
</td>
</tr>
</table>
到目前为止,这是我的JQuery:
$.getJSON(serverURL,{ id: X },
function(data) {
$.each(data, function(key,val){
var clonedDiv= $('#Template').clone();
//"Each" below represents the various data members of the object currently being processed.
$.each(val,function(key2,value){
//Below are the only Keys needed so skip the rest.
if (key2=='Id' || key2=='Name' || key2=='Addr' || key2=='City' || key2=='State' || key2=='Zip'){
alert('Key2:'+key2+' val2:'+JSON.stringify(value));
///INSERT VALUE INTO NEWLY-CLONED DIV SPAN CHILD HERE???
}
});
$('#TemplatePrev').append(clonedDiv);
});
})
.success(function() {
alert('success');
})
.error(function() { alert('error'); })
.complete(function() {
//alert('complete');
});
运行上述操作时,JSON调用返回10个对象,JQuery克隆10个DIV,看起来像#Template div。但是,我需要动态地将JSON Stringified值推入每个范围。知道怎么做吗?我在这里待了2个小时才打破并在这里发帖。提前谢谢!
答案 0 :(得分:0)
您是否尝试过以下操作?
if (key2=='Id' || key2=='Name' || key2=='Addr' || key2=='City' || key2=='State' || key2=='Zip'){
clonedDiv.find('.' + key2).text(JSON.stringify(value));
}
答案 1 :(得分:0)
或许这样的事情:
clonedDiv.find('span.'+key2).text(JSON.stringify(value));
答案 2 :(得分:0)
显而易见的解决方案是使用模板化解决方案为您完成此任务。我想到的一对是Handlebars,Pure或Underscore Templates。
否则这样的事情应该有效:
clonedDiv.find("." + key2).text(value)
@andreas对于复制id也是正确的,尽量避免这种情况。
答案 3 :(得分:0)
<script type="text/javascript">
$(document).ready(function() {
makeClone();
});
function makeClone() {
for (i = 0; i < 5; i++) {
var cloneing = $('.divclone').clone();
$('#container').append(cloneing.removeClass().attr("id",'new'+i));
}
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div id="container" >
<div class="divclone">
this is it
</div>
</div>