Javascript $.add 和 $.append JQuery 有什么区别
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10893302/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What's the difference between $.add and $.append JQuery
提问by Zahid Riaz
I was wondering and couldn't get any best documentation that what's the difference between $.add and $.append when we have single element to add or append to a container.
我想知道并且无法获得任何最佳文档,说明当我们将单个元素添加或附加到容器时 $.add 和 $.append 之间有什么区别。
Thanks in Advance
提前致谢
采纳答案by Kamran Ali
Given a jQuery object that represents a set of DOM elements, the .add()
method constructs a new jQuery object from the union of those elements and the ones passed into the method. But it does not insert the element into the DOM, i.e using .add()
the element will be added to the DOM but to see it in the page you have to insert it in the page using some insertion/appendmethod.
给定一个表示一组 DOM 元素的.add()
jQuery 对象,该方法根据这些元素和传递给该方法的元素的联合构造一个新的 jQuery 对象。但它不会将元素插入到 DOM 中,即使用.add()
元素将被添加到 DOM 中,但要在页面中查看它,您必须使用一些插入/追加方法将其插入页面中。
回答by Jashwant
They are not at all related.
它们完全没有关系。
.add()
。添加()
Add elements to the set of matched elements.
将元素添加到匹配元素的集合中。
e.g.
例如
If you want to do,
如果你想做,
$('div').css('color':'red');
$('div').css('background-color':'yellow');
$('p').css('color':'red');
Then, you can do,
那么,你可以这样做,
$('div').css('background-color':'yellow').add('p').css('color':'red');
.append()
。附加()
Insert content, specified by the parameter, to the end of each element in the set of matched elements.
将参数指定的内容插入到匹配元素集中每个元素的末尾。
$('div').append('p');
will append selected p
on all selected div
in dom.
将在 dom 中的p
所有选定项上附加选定项div
。
回答by tismle
.add()
。添加()
for example:
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
</ul>
<p>a random paragraph</p>
to change the color of the <li>
elements ANDthe <p>
element to red, you could write:
改变的色彩<li>
元素和的<p>
元素,以红色,你可以写:
$( "li" ).css( "background-color", "green" );
$( "p" ).css( "background-color", "green" );
or condensing the above by utilizing .add()
或使用 . 添加()
$( "li" ).add( "p" ).css( "background-color", "green" );
.append()
。附加()
Will createa new element to add to the DOM and will appear as a child to the existing specified element.
将创建一个新元素以添加到 DOM,并将作为现有指定元素的子元素出现。
<div>one</div>
<div>two</div>
<ol>
<li>item1</li>
<li>item2</li>
</ol>
$("div").append('<p>');
will result in:
将导致:
<div>one</div>
<p></p>
<div>two</div>
<p></p>
<ol>
<li>item1</li>
<p></p>
<li>item2</li>
<p></p>
</ol>
回答by Porco
Add just adds the element to the jquery object, it does not add it into the DOM
Add 只是将元素添加到 jquery 对象中,不会将其添加到 DOM 中
Append adds the element into the DOM as the child.
Append 将元素作为子元素添加到 DOM 中。