如何通过jQuery构建JSON和构建HTML [英] How to structure JSON and build HTML via jQuery
问题描述
这里的初学者试图找出构造一些JSON并输出以下嵌套的< ul>
的最佳方法以下每个加粗的项目都是JSON中的值.如何构造JSON,然后如何使用jQuery构建DOM结构?任何帮助都将不胜感激.
您可以使用类似DOM的方法来设置属性和文本内容,从而避免普通html()
-setting和较简单的模板系统.例如,使用jQuery 1.4并结合calvinf的示例使用JSON输入:
var ul0= $('<ul>');
$.each(topics, function() {
var li0= $('<li>', {text: this.title});
var ul1= $('<ul>');
$.each(this.items, function() {
ul1.append($('<li>', {id: 'foo_'+this.title})
.append($('<a>', {href: this.link, text: this.text})
.append($('<strong>', {text: this.data0}))
.append($('<span>', {text: this.data1}))
.append($('<em>', {text: this.data2}))
)
);
});
li0.append(ul1);
ul0.append(li0);
});
Beginner here trying to figure out best way to structure some JSON and output the below nested <ul>
Each of the bolded items below are the values in the JSON. How might I structure the JSON and then how to build the DOM structure with jQuery? Any help greatly appreciated.
<ul> <li>Topic 1 <ul> <li id="foo_item1a"> <a href="destination_Item1a"> <strong>Lorem</strong> <span>Item 1a</span> <em>Ipsum</em> </a> </li> <li id="foo_item1b"> <a href="destination_Item1b"> <strong>Dolor</strong> <span>Item 1b</span> <em>Sit</em> </a> </li> </ul> </li> <li>Topic 2 <ul> <li id="foo_item2a"> <a href="destination_Item2a"> <strong>Lorem</strong> <span>Item 2a</span> <em>Ipsum</em> </a> </li> <li id="foo_item2b"> <a href="destination_Item2b"> <strong>Dolor</strong> <span>Item 2b</span> <em>Sit</em> </a> </li> </ul> </li> </ul>
You can use DOM-like methods to set attributes and text content instead to avoid the HTML-escaping issues you'll have with plain html()
-setting and the more naïve of the templating systems. For example using jQuery 1.4 and with JSON input along the lines of calvinf's example:
var ul0= $('<ul>');
$.each(topics, function() {
var li0= $('<li>', {text: this.title});
var ul1= $('<ul>');
$.each(this.items, function() {
ul1.append($('<li>', {id: 'foo_'+this.title})
.append($('<a>', {href: this.link, text: this.text})
.append($('<strong>', {text: this.data0}))
.append($('<span>', {text: this.data1}))
.append($('<em>', {text: this.data2}))
)
);
});
li0.append(ul1);
ul0.append(li0);
});
这篇关于如何通过jQuery构建JSON和构建HTML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!