我正在处理 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;
}
}); Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
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'); }