Javascript 如何使用jQuery检查图像URL是否为空并执行某些操作?
我正在用PHP从另一个站点加载XML提要。我的HTML输出如下:Javascript 如何使用jQuery检查图像URL是否为空并执行某些操作?,javascript,php,jquery,html,Javascript,Php,Jquery,Html,我正在用PHP从另一个站点加载XML提要。我的HTML输出如下: <div class="sponsored"> <div class='box'><img src='http:///xxx.jpg'><a href='xxx'>Title</a></div> <div class='box'><img src='http:///xxx.jpg'><a href='xxx'>Title&
<div class="sponsored">
<div class='box'><img src='http:///xxx.jpg'><a href='xxx'>Title</a></div>
<div class='box'><img src='http:///xxx.jpg'><a href='xxx'>Title</a></div>
<div class='box'><img src='http:///xxx.jpg'><a href='xxx/'>Title</a></div>
<div class='box'><img src=''><a href='xxx'>Title</a></div>
</div>
谢谢大家的回答!!以下是像我这样的未来noob的最终工作代码:
<script>
$(document).ready(function(){
$(".sponsored > .box > img[src='']").attr("src","image.jpg");
});
</script>
您可以使用“属性等于选择器”执行此操作
$(".sponsored > .box > img[src='']").attr("src","default.png");
您可以这样使用,此示例将为您提供3条非空记录和1条空记录,您可以在浏览器控制台中检查结果: $'.box img'.eachfunctionindex,val{ 如果$this.attr'src'=={ console.log'empty'; } 否则{ 控制台。日志“不为空”; } }; 试试这个
$('.box img').each(function(){
if($(this).attr('src') == ''){
//do something
}
else{
//do something
}
});
奇怪的是,它没有将default.png添加到code@reizer看一看。它应该会起作用。如果不是的话,你能在一把新的小提琴上复制同样的东西吗?thanx,但我不能让它工作,因为某些原因。。。它没有向空图像的url属性添加任何内容使用$this.attr'src','default.png';
$('.sponsored .box img').each(function () {
if (this.src!== undefined && this.src!='') {
console.log("Exists");
}else
{
console.log("Not Exists");
}
});
$(document).ready(function(){
$(".sponsored .box img").each(function(){
if($(this).attr('src') == ''){
$(this).attr('src') = 'default.png';
}
});
});
$('.box img').each(function(){
if($(this).attr('src') == ''){
//do something
}
else{
//do something
}
});