[英]How to create multiple HTML elements with jQuery?
What I'm trying to do is to create a table pager control using jQuery.我想要做的是使用 jQuery 创建一个表格分页器控件。 It contains lots of links and spans.
它包含许多链接和跨度。 I've managed to do this with plain string concatenation, but I can't believe that jQuery can't make this more elegant.
我已经设法用普通的字符串连接来做到这一点,但我不敢相信 jQuery 不能让它更优雅。 I can't use jTemplates here since the generation has quite a bit of procedural logic.
我不能在这里使用 jTemplates,因为这一代有相当多的程序逻辑。
Question: is there a way to create an array of HTML elements with jQuery and append them to some container?问题:有没有办法用 jQuery 创建一个 HTML 元素数组并将它们附加到某个容器中?
Thanks.谢谢。
$('First Element').add($('Second Element')).appendTo($('body'))
String concatenation (or Array.join) is fine, as long as you make it pretty ;)字符串连接(或 Array.join)很好,只要你让它漂亮;)
var structure = [
'<div id="something">',
'<span>Hello!</span>',
'</div>'
];
$(structure.join('')).appendTo(container);
There is always append() .总是有append() 。
$('#container').append('<span>foobar baz</span>');
It seems to me that just using string concatenation and append would be the least complex, and probably fastest option.在我看来,仅使用字符串连接和追加将是最简单的,也可能是最快的选择。 However, following is an untested example of a way to (arguably) simplify the creation of elements, and allow you to append them to a given parent element:
但是,以下是一个未经测试的示例,它可以(可以说)简化元素的创建,并允许您将它们附加到给定的父元素:
function elemCreate(type, content, attrs) {
/* type: string tag name
* content: string element content
* attrs: associative array of attrs and values
*/
elem = '<' + type + '></' + type + '>'
e = $(elem).attr(attrs)
e.append(content)
return e
}
stuff = [];
stuff.push(elemCreate('a', 'Click me!', {'href': 'http://stackoverflow.com'});
$(stuff).appendTo($('#container'));
You can just simplify things by doing like this :)你可以通过这样做来简化事情:)
$('.parentElement').append(`
<table style="width:100%">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>Age</th>
</tr>
<tr>
<td>Jill</td>
<td>Smith</td>
<td>50</td>
</tr>
</table>
`);
Just need to used `` or back quote inside the append method只需要在 append 方法中使用 `` 或反引号
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.