如何跳过 document.querySelectorAll 值为 null 或不存在
Posted
技术标签:
【中文标题】如何跳过 document.querySelectorAll 值为 null 或不存在【英文标题】:how to skip document.querySelectorAll value is null or does not exist 【发布时间】:2022-01-20 19:52:40 【问题描述】:<script>
(function()
var data =
"@context": "https://schema.org",
"@type": "Movie",
"actor": [],
for (i = 0; i < document.querySelectorAll('span.movie-cast-title').length; i++)
if (!document.querySelectorAll('span.gcharacter')[i])
data.actor.push(
"@type": "PerformanceRole",
"actor":
"@type": "Person",
"name": document.querySelectorAll('span.movie-cast-title')[i].innerText,
"url": document.querySelectorAll('a.movie-cast-url')[i].href,
,
"characterName": document.querySelectorAll('span.gcharacter')[i].innerText,
);
else
data.actor.push(
"@type": "PerformanceRole",
"actor":
"@type": "Person",
"name": document.querySelectorAll('span.movie-cast-title')[i].innerText,
"url": document.querySelectorAll('a.movie-cast-url')[i].href,
,
);
;
var script = document.createElement('script');
script.type = "application/ld+json";
script.innerhtml = JSON.stringify(data);
document.getElementsByTagName('head')[0].appendChild(script);
)(document);
</script>
如何跳过“characterName”:document.querySelectorAll('span.gcharacter')[i].innerText,值为空。 for is const characterName is does not exist 仅跳过 characterName var。 if else 语句是正确的还是使用其他 any 语句?
【问题讨论】:
【参考方案1】:要走的路是创建一个对象来存储始终存在的属性。然后,如果 characterName 不为空,则将此属性添加到对象并将其推送到 data.actor 数组:
var actor =
"@type": "PerformanceRole",
"actor":
"@type": "Person",
"name": document.querySelectorAll('span.movie-cast-title')[i].innerText,
"url": document.querySelectorAll('a.movie-cast-url')[i].href
if (!document.querySelectorAll('span.gcharacter')[i])
actor["characterName"] = document.querySelectorAll('span.gcharacter')[i].innerText
data.actor.push(actor)
【讨论】:
以上是关于如何跳过 document.querySelectorAll 值为 null 或不存在的主要内容,如果未能解决你的问题,请参考以下文章