从附加元素获取 jQuery 对象的更简单方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1443233/
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
Easier way to get a jQuery object from appended element
提问by slolife
Is there an easier/quicker way to get the element added using jQuery append:
是否有更简单/更快的方法来使用 jQuery append 添加元素:
How to get the $selectors element:
如何获取 $selectors 元素:
$container.append('<div class="selectors"></div>');
var $selectors = $('.selectors', $container);
I tried:
我试过:
var $selectors = $container.append('<div class="selectors"></div>');
but that makes $selectors = $container
但这使得 $selectors = $container
Maybe that's the quickest/best way. Just checking.
也许这是最快/最好的方法。只是检查。
回答by cletus
Why not just:
为什么不只是:
var el = $('<div class="selectors"></div>');
$container.append(el);
?
?
Then you have access to 'el'.
然后你就可以访问'el'。
回答by Magnar
This is my favourite way of doing it:
这是我最喜欢的做法:
var $selectors = $('<div class="selectors"></div>').appendTo(container);
回答by hobbs
$selectors = $('<div/>').addClass('selectors').appendTo($container);
回答by Brad Parks
You could also create a new jQuery function to do it:
您还可以创建一个新的 jQuery 函数来执行此操作:
jQuery.fn.addChild = function(html)
{
var target = $(this[0])
var child = $(html);
child.appendTo(target);
return child;
};
and then use it like so:
然后像这样使用它:
$('<ul>').addChild('<li>hi</li>');
of course if you wanted to add more than one item:
当然,如果您想添加多个项目:
var list = $('<ul>');
list.addChild('<li>item 1</li>');
list.addChild('<li>item 2</li>');
The advantage of approaches like this is that later on you can add more to the "addChild" function if you like. Note that for both the examples above, you need to add the element to the document, so a full example might be:
此类方法的优点是,稍后您可以根据需要向“addChild”函数添加更多内容。请注意,对于上面的两个示例,您都需要将元素添加到文档中,因此完整示例可能是:
$('body').addChild('<ul>').addChild('<li>hi</li>');