简体   繁体   English

如何使用JQuery在空文档中附加HTML标签?

[英]How to append HTML tags in empty document with JQuery?

I have a function that returns a list of HTML elements to be added to another tag. 我有一个函数,该函数返回要添加到另一个标签的HTML元素列表。 This function is meant to be called as follow: 该函数的含义如下:

$('#somewhere').append(getElements())

To test the feasibility I wrote this: 为了测试可行性,我这样写:

var el = $() 

for (u in ['foo', 'bar']) {
    el.append($('<li>').addClass(u).text(u + 'Text'))
}

$('<ul>').append(el).html()

Eventually I get nothing into <ul> . 最终,我什么都没进入<ul> Why? 为什么? Where is my mistake? 我的错误在哪里? I suspect the $() to not work as wanted because if I do var el = $('<div>') instead, then it works. 我怀疑$()不能按需要工作,因为如果我做var el = $('<div>') ,那么它就可以工作。

Note 注意

I could have used: 我本可以使用:

getElementsInto('#somewhere')

But I would prefer: 但我希望:

$('#somewhere').append(getElements())

append appends the given elements to every element in the jQuery set you call it on. append将给定元素附加到您调用它的jQuery集合中的每个元素。 $() is an empty jQuery set, so append on it is a no-op. $()是一个空的jQuery集,因此append在它上面是一个空操作。 There are no elements to append to. 没有要追加的元素。 (Also note that you're using the wrong style of loop to loop through an array; in your loop, u will be "0" and then "1" .) Also, calling .html() without using the return value is a no-op. (还请注意,您使用了错误的循环样式来遍历数组;在循环中, u将为"0" ,然后为"1" 。)此外,不使用返回值调用.html()也是无操作。

add would create a new jQuery object with the additions: add将创建一个带有以下内容的新jQuery对象:

 var elements = $(); ['foo', 'bar'].forEach(function(u) { elements = elements.add($('<li>').addClass(u).text(u + 'Text')); }); var ul = $('<ul>').append(elements); // then append `ul` somewhere... ul.appendTo(document.body); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

...but I think I'd build up the elements in an array. ...但是我想我会在数组中建立元素。 In your case, since your starting point is an array, you can use map : 在您的情况下,由于起点是数组,因此可以使用map

 var elements = ['foo', 'bar'].map(function(u) { return $('<li>').addClass(u).text(u + 'Text'); }); var ul = $('<ul>').append(elements); // then append `ul` somewhere... ul.appendTo(document.body); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM