【问题标题】:how to skip document.querySelectorAll value is null or does not exist如何跳过 document.querySelectorAll 值为 null 或不存在
【发布时间】: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 语句?

【问题讨论】:

    标签: if-statement schema google-tag-manager


    【解决方案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)
    

    【讨论】:

      猜你喜欢
      • 2022-01-20
      • 1970-01-01
      • 1970-01-01
      • 2021-09-13
      • 1970-01-01
      • 2013-06-13
      • 2019-05-18
      • 1970-01-01
      • 2021-10-27
      相关资源
      最近更新 更多