Jquery 对于每个函数中的特定div id,如何知道div内容是否为空?
我需要检查每个函数中的特定div id内容是否为空。如果div内容是empy,我想在那里放一条“请点击此处添加图片”的短信。但我的代码不起作用 我有这样一个html:Jquery 对于每个函数中的特定div id,如何知道div内容是否为空?,jquery,Jquery,我需要检查每个函数中的特定div id内容是否为空。如果div内容是empy,我想在那里放一条“请点击此处添加图片”的短信。但我的代码不起作用 我有这样一个html: <div class="wrapper"> <div class="list"> <div class="item"><div id="image">image</div></div> <div class="item"><div id="t
<div class="wrapper">
<div class="list">
<div class="item"><div id="image">image</div></div>
<div class="item"><div id="test">test</div></div>
<div class="item"><div id="image"></div></div>
<div class="item"><div>test</div></div>
<div class="item"><div id="image"><a href="test.html"><img src="https://via.placeholder.com/100x75.png"></a></div></div>
</div>
</div>
<div class="wrapper">
<div class="list">
<div class="item"><div id="image">Please click to here for add a image</div></div>
<div class="item"><div id="test">test</div></div>
<div class="item"><div id="image">Please click to here for add a image</div></div>
<div class="item"><div>test</div></div>
<div class="item"><div id="image"><a href="test.html"><img src="https://via.placeholder.com/100x75.png"></a></div></div>
</div>
</div>
我的JSFIDLE代码如下:
您的代码中存在多个问题
class
对多个元素进行分组$(“.item#image”).html(..)
)元素来更新所有元素(即使它不会在当前代码中选择)要使其工作,请使用类对元素进行分组,然后使用获取空元素。实际上,在您的案例中不需要使用方法,因为您希望用相同的内容更新所有元素
$(文档).ready(函数(){
$(“.list.image:empty”).html(“请单击此处添加图像”);
});代码>
形象
测试
测试
您还可以像下面这样更改代码
if($(this).is(':empty')) { $(this).html("Please click to here for add a image"); }
我刚刚修改了你的代码,这样你就可以得到结果了
$(document).ready(function(){
$(".list > .item").each(function() {
var tag = $(this).children('#image');
if(tag.length)
{
if(tag.html().length===0)
{
tag.html('Please click to here for add a image');
}
}
});
);
id应该是唯一的,因此请使用class和update Selector。在您的示例中,第一个#image
div不是空的,但它的内容已被替换。非常感谢您的回答和代码。此时我需要使用div类名称的div id istead。但你们的答案对解决类名问题很有帮助。非常感谢你们的答案和代码。你的代码也在工作。非常有助于以不同的方式使用div id解决方案。非常感谢您的回答和代码。这种方式对我来说是一个更好的简短解决方案。
if($(this).is(':empty')) { $(this).html("Please click to here for add a image"); }
$(document).ready(function(){
$(".list > .item").each(function() {
var tag = $(this).children('#image');
if(tag.length)
{
if(tag.html().length===0)
{
tag.html('Please click to here for add a image');
}
}
});
);