jQuery动态创建html元素的常用方法汇总

2020-05-22 17:04:50易采站长站整理

id: "myLink",
href: "http://www.baidu.com"
});

$('#wrap1').append(a);

var input = buildHTML("input", {
id: "myInput",
type: "text",
value: "我也是由模版生成的~~"
});

$('#wrap2').append(input);
});

buildHTML = function(tag, html, attrs) {
// you can skip html param
if (typeof (html) != 'string') {
attrs = html;
html = null;
}
var h = '<' + tag;
for (attr in attrs) {
if (attrs[attr] === false) continue;
h += ' ' + attr + '="' + attrs[attr] + '"';
}
return h += html ? ">" + html + "</" + tag + ">" : "/>";
};
</script>
</head>
<body>
<div id="wrap1"></div>
<div id="wrap2"></div>
</body>

运行效果如下图所示:

相信本文所述对大家使用jQuery进行WEB程序设计有一定的借鉴价值。