如何使用 jquery 创建这些嵌套的 dom 元素? [英] How do I create these nested dom elements with jquery?
本文介绍了如何使用 jquery 创建这些嵌套的 dom 元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定这些 javascript 变量:
var div_id = "my_div";var h1_class = "my_header";var a_class = "my_a_class";var a_string = "teststring";
和这个页面元素:
<div id="container"></div>
我想用 jQuery 构建这个 html 结构:
<div id="my_div"><h1 class="my_header"><a href="/test/" class="my_a_class">teststring</a>
在此处链接命令的最佳和最易读的方式是什么?
解决方案
UPDATED
<块引用>JSON
var widgets = [{div":{id":我的div-1"},h1":{类":我的标题"},一个" : {"class" : "my-a-class",文本":谷歌","href" : "http://www.google.com"}}, {div":{"id" : "my-div-2"},h1":{类":我的标题"},一个" : {"class" : "my-a-class","text": "雅虎","href" : "http://www.yahoo.com"}}];$(函数(){$.each(widgets, function(i, item) {$('<div>').attr('id', item.div.id).html($('').attr('class', item.h1.class).html($('').attr({'href' : item.a.href,'class' : item.a.class}).text(item.a.text))).appendTo('#container');});});
Given these javascript variables:
var div_id = "my_div";
var h1_class = "my_header";
var a_class = "my_a_class";
var a_string = "teststring";
and this page element:
<div id="container"></div>
I want to build this html structure with jQuery:
<div id="container">
<div id="my_div">
<h1 class="my_header">
<a href="/test/" class="my_a_class">teststring</a>
</h1>
</div>
</div>
What is the best and most readable way to chain the commands here?
解决方案
UPDATED
JSON
var widgets = [{
"div" : {
"id" : "my-div-1"
},
"h1" : {
"class" : "my-header"
},
"a" : {
"class" : "my-a-class",
"text" : "google",
"href" : "http://www.google.com"
}
}, {
"div" : {
"id" : "my-div-2"
},
"h1" : {
"class" : "my-header"
},
"a" : {
"class" : "my-a-class",
"text" : "yahoo",
"href" : "http://www.yahoo.com"
}
}];
$(function() {
$.each(widgets, function(i, item) {
$('<div>').attr('id', item.div.id).html(
$('<h1>').attr('class', item.h1.class).html(
$('<a>').attr({
'href' : item.a.href,
'class' : item.a.class
}).text(item.a.text))).appendTo('#container');
});
});
这篇关于如何使用 jquery 创建这些嵌套的 dom 元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文