Javascript jQuery - 如果不存在则创建元素 - 一种更短的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6419632/
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
jQuery - create element if doesn't exist - a shorter way
提问by Alex
How can I find out if a certain element has another element as a child? And if it doesn't, append a new one to it and then return it.
如何确定某个元素是否有另一个元素作为子元素?如果没有,则附加一个新的,然后返回它。
I tried it with:
我试过:
var myel = ($('> div.my', this).length > 0)
? $('> div.my', this)
: $(this).append('<div class="my"></div>').css('opacity', 0);
but even though it creates my element if it doesn't exist, it doesn't return it...
但即使它创建我的元素,如果它不存在,它也不会返回它......
回答by glortho
How about this?
这个怎么样?
var myel = $('> div.my', this).length ? $('> div.my', this) : $('<div class="my"></div>').css('opacity', 0).appendTo(this);
回答by Alastair Pitts
This is how I would do it:
这就是我将如何做到的:
var myDivs = $('div.container').children('div.my');
if(myDivs.length === 0){
myDivs = $('<div class="my"></div> ')
.appendTo('div.container')
.css('opacity', 0);
}
My reasoning is that you only need to query the children once, so if there is a lot of children, this will save some time.
我的推理是你只需要查询一次孩子,所以如果孩子很多,这会节省一些时间。
Also, if there is no children, then you create one, appendTo
the container, perform css and then return it.
此外,如果没有孩子,那么您创建一个appendTo
容器,执行 css 然后返回它。
回答by kinakuta
Similar to Alastair's method, but using filters:
类似于 Alastair 的方法,但使用过滤器:
$('div.outerDiv:not(:has(div.my))').each(function(){
$('<div class="my"></div>')
.appendTo(this)
.css('opacity', 0);
});
回答by ptrk
Late I know, but a different approach, adding syntactic sugar and making things legible IMO:
我知道的晚了,但采用了不同的方法,添加语法糖并使 IMO 清晰易读:
function ifNotExists($x){
if(!$x || $x.length === 0) return { create : function(newX){ return newX; }}
else return { create : function(){ return $x } };
}
//usage:
$someDiv.append(ifNotExists("div.child").create("<div class='child'>"));