首页 > 解决方案 > HTML 中的多个脚本标签未按顺序执行

问题描述

请在整页中查看代码片段的结果

我试图从一组嵌套的 HTML 元素中获取文本内容,这些元素显然是在运行时由脚本/API附加的。


请注意quote_text&是API/脚本在运行时children[j]附加的元素 。因此它不是我直接控制的。(我使用检查元素找到了它们)所以我尝试使用 javascript 更改它们,因为它们不直接在我的控制范围内。

然而,碰巧的是,即使负责附加样式引用的脚本/API 中有内容,当尝试使用脚本将其内容设置为另一个 div 时,它也会显示为空白

为什么会发生这种情况,我该如何实现呢?

我这样做的原因是,我不想要 API 给出的格式样式。相反,我希望它以我的方式设计。

html,
body {
  margin: 0;
  padding: 0;
  /*height:100%;
    overflow:hidden;*/
  overflow: hidden;
}

header {
  background-color: black;
  height: 100vh;
  background-size: cover;
  background-position: center;
}


/******* QUOTE *********************************************************/

.center_bottom {
  position: absolute;
  right: 10px;
  bottom: -20px;
}

a {
  pointer-events: none;
  cursor: default;
}

.quote_div2 {
  display: block;
  color: white;
  font-size: 20px;
  font-family: Arial;
  position: absolute;
  left: 10px;
  top: 15px;
}
<!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" href="1.css">
  <script type="text/javascript" src="https://theysaidso.com/gadgets/v3/theysaidso.js"></script>

</head>

<body>

  <header>
    <!-- PART1 -->
    <!-- DIV1: This below script fetches a Quote & displays it in styled fashion -->
    <div id="quote_div" class="tso_simple_borders center_bottom q-t">
      <script id="sc1">
        TheySaidSo.render({
          qod_category: 'inspire'
        });
        //document.getElementById("quote_div").style.display = "none";
      </script>
    </div>
    
    
    
    <!-- PART2 -->
    <!-- DIV2: This is division where i want to paste the plain text from DIV1-->
    <div class="quote_div2">
      <span id="spn"></span>
    </div>
    
    
    
    <!-- PART3 -->
    <!-- In this script, I'm trying to fetch Quote contents and set it onto other div -->
    <script>
      var txt = "This text should be replaced by ONLY TEXT CONTENTS of below quote";
      var qttxt = document.getElementsByClassName("quote_text");
      Array.from(qttxt).forEach((el) => {
        var children = el.childNodes;
        if (el.nodeName.toLowerCase() == 'span') {
          el.style.color = "white";
        }
        for (var j = 0; j < children.length; j++) {
          if (children[j].nodeName.toLowerCase() == 'a') {
            txt = txt + children[j].innerHTML;
          }
        }
      });

      document.getElementById("spn").innerHTML = txt;
    </script>

  </header>

</body>

</html>


**

对于那些对此感到困惑的人quote_text,它附加在后端(请查看下图以供参考):

** 在此处输入图像描述


问题似乎在于脚本的执行顺序。
为了让它工作,PART1 脚本应该首先完成执行和渲染报价框,然后再执行 PART3 脚本。
但似乎是在 PART1 甚至完成执行之前, PART3 已执行!(这不应该发生)

标签: javascripthtmlcssdommutation-observers

解决方案


推荐阅读