从附加元素获取 jQuery 对象的更简单方法

使用 jQuery append 添加元素是否有更简单/更快捷的方法:

如何获得 $selector 元素:

$container.append('<div class="selectors"></div>');
var $selectors = $('.selectors', $container);

我试过:

var $selectors = $container.append('<div class="selectors"></div>');

但是这使得 $selector = $Container

也许这是最快/最好的方式。只是检查。

63202 次浏览

Why not just:

var el = $('<div class="selectors"></div>');
$container.append(el);

?

Then you have access to 'el'.

This is my favourite way of doing it:

var $selectors = $('<div class="selectors"></div>').appendTo(container);
$selectors = $('<div/>').addClass('selectors').appendTo($container);

You could also create a new jQuery function to do it:

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:

$('body').addChild('<ul>').addChild('<li>hi</li>');