jQuery 如果元素不为空则添加内容
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10449218/
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
Add content if element is not empty
提问by Puyol
HTML:
HTML:
<div id="parent">
<div class="child"></div>
<div class="child"><p>Div with content<p></div>
<div class="child"><img scr="pic.png" alt="Div with picture" /></div>
</div>
Result I want:
我想要的结果:
<div id="parent">
<div class="child"></div>
<div class="child"><h1>title</h1><p>Div with content<p></div>
<div class="child"><h1>title</h1><img scr="pic.png" alt="Div with picture" /></div>
</div>
My jQuery code:
我的jQuery代码:
$(".child").each(function() {
if ($(this).html != '')
$(this).prepend('<h1>title</h1>');
});
Result with my jQuery code:
结果与我的 jQuery 代码:
<div id="parent">
<div class="child"><h1>title</h1></div>
<div class="child"><h1>title</h1><p>Div with content<p></div>
<div class="child"><h1>title</h1><img scr="pic.png" alt="Div with picture" /></div>
</div>
So I just want to add a title to every div of a certain class that's not empty.
所以我只想为某个非空类的每个 div 添加一个标题。
回答by Evan Mulawski
回答by Chuck Norris
$(".child").each(function() {
if ($(this).html())
$(this).prepend('<h1>title</h1>');
});
回答by Chuck Norris
$("#parent .child").each(function() {
if ($.trim($(this).html()).length > 0 )
$(this).prepend('<h1>title</h1>');
});
回答by Starx
Use length to check instead.
改用长度来检查。
$(".child").each(function() {
if ($(this).html().length)
$(this).prepend('<h1>title</h1>');
});
回答by Shikiryu
You got an unclosed <p>
and to get the selector's html, you use a function, not an attribute :
你有一个未关闭的<p>
,为了获得选择器的 html,你使用了一个函数,而不是一个属性:
$(this).html()
your fiddle http://jsfiddle.net/bCKGV/
你的小提琴 http://jsfiddle.net/bCKGV/
回答by Vimalnath
Try this:
尝试这个:
$(".child:not(:empty)").prepend('<h1>title</h1>');
OR:
或者:
$("#parent .child").each(function() {
if ($(this).html())
$(this).prepend('<h1>title</h1>');
});