检查 img src 标签是否为空或 null 或未定义
P粉111227898
P粉111227898 2024-03-28 09:36:47
[HTML讨论组]

我正在处理 JSON 数据并处理该数据以将其插入到正确的 html 标签中。有时 JSON 数据不包含信息或根本不可用。在给定的示例中,src 为空或踢脚器不存在,这会在这一行给出类似 {} 或 undefined 或 '' 或 null 的结果:

document.getElementById("placeholder_" + (k)).src = jsonData[i].src;

我在板上寻找解决方案并尝试过,但没有成功。或者说我没有理解这个逻辑。一些对我不起作用的例子:

document.getElementById('id2').src = json.img2 ? json.img2.link : 'defaultLink';

或者我查阅了此链接:

JSON 有时未定义 - 我该如何检查?

这是我的代码片段,我想检查 jsonData[i].src 中是否有数据(网址)。我怎样才能做到这一点? 在第二部分中,src 为空,在第三部分中,踢球器丢失。如何检查?

var jsonData = [
    {
    src: 'https://www.w3schools.com/tags/img_girl.jpg',
    kicker: 'Kyiv',
    headline: 'Grief and defiance in city on first anniversary of war in Ukraine',
  },
  {
    src: '',
    kicker: 'Russia',
    headline: 'how can Ukraine win? And what is the feeling within Russia?',
  },
  {
    src: 'https://www.w3schools.com/tags/img_girl.jpg',
    
    headline: 'how can Ukraine win? And what is the feeling within Russia?',
  }
  ]
  
 $(document).ready(function () {
    var k = 1;
    //loop through json data and insert into corresponding divs
    for (var i = 0; i < jsonData.length; i++) {
        document.getElementById("placeholder_" + (k)).src = jsonData[i].src;
        document.getElementById("placeholder_" + (k = k + 1)).innerText = jsonData[i].kicker;
        document.getElementById("placeholder_" + (k = k + 1)).innerText = jsonData[i].headline;
        k = k + 1;
    }
    });

P粉111227898
P粉111227898

全部回复(1)
P粉662614213
const imgElement = document.querySelector('img');
const imgSrc = imgElement.getAttribute('src');

if (!imgSrc || imgSrc.trim() === '') {
  console.log('Image src is empty, null or undefined');
} else {
  console.log('Image src is not empty');
}
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习
PHP中文网抖音号
发现有趣的

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号