【问题标题】:jQuery html script document.currentScriptjQuery html 脚本 document.currentScript
【发布时间】:2018-07-27 10:18:18
【问题描述】:

我使用 html(),但找不到在父脚本中获取变量的方法。

child.html

<section class="mod_el">
    <div id="any_element"></div>
</section>
<script type="text/javascript">
    document.currentScript.childVar = {
        parameterOne:"ONE"
    };
</script>

parent.html

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <div id="container"></div>
    <script>
        async function LoadChild() {
            const resp = await fetch(`child.html`, {
                method: "GET",
                credentials: "include"
            });
            if (!resp.ok)
                return;
            const result = await resp.text();
            $("#container").html(result);
            console.log(childVar.parameterOne); //!!!!!!! ?????
            //^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        }
        LoadChild();
    </script>
</body>
</html>

在parent.html中获取变量“childVar”值的可能方法是什么?

非常感谢您的帮助

更新 - 寻找解决方案 用这种方式解决了问题(不用jquery)但是结果找到了..

在child.html中需要设置

document.currentScript.ownerDocument.childVar = {
            parameterOne:"ONE"
        };

在 parent.html 中

const link = document.createElement('link');
link.rel = 'import';
link.href = `child.html`;
link.setAttribute('async', '');
link.onload = (e) => {
                    console.log(link.import.childVar.parameterOne );
                };
document.head.appendChild(link);

【问题讨论】:

  • 如果您将变量定义为document.currentScript.childVar,您需要使用相同的路径来访问它。所以console.log(document.currentScript.childVar);
  • 谢谢,但它不起作用。我忘了写 rawHtmlText 是一个外部文件。
  • 这完全取决于你如何在 dom 中加载脚本,父脚本应该低于你在原始 html 文件中提到的脚本或在外部脚本的情况下加载
  • Î 需要从 child.html 中读取的变量 parent.html
  • 您不能在脚本中设置 currentScript 键!它只是返回当前脚本元素 >>>

标签: javascript jquery document


【解决方案1】:

我认为document.currentScript 不会像您认为的那样做。它返回对当前正在执行的&lt;script&gt; 标记的DOM 元素的引用。所以当你给document.currentScript.someVar赋值时,你不是在创建一个全局变量或类似的东西,你是在当前执行的&lt;script&gt;标签上创建一个expando property

但是,在这种情况下,由于您是在由.html 创建的代码内部调用它,所以document.currentScript 实际上是对调用.html&lt;script&gt; 标记的引用。如果在插入 HTML 后,我们在 #parentDiv 之后查询 script 标记,我们可以看到这一点。

由于 JS 不喜欢字符串中的&lt;/script&gt; 标签,以下示例中的 HTML 是 URI 编码的。

在这个例子中实际注入的 HTML 是:

<script>
  document.currentScript.childVar = {
    foo: 'bar'
  };
</script>

var rawHtmlText = decodeURI(`%3Cscript%3E%0A%20%20document.currentScript.childVar%20=%20%7B%0A%20%20%20%20foo:%20'bar'%0A%20%20%7D;%0A;%3C/script%3E%0A`);
$("#parentDiv").html(rawHtmlText);

// This script block is inserted after #parentDiv, so use
// the sibling combinator to get a reference to it.
console.log($('#parentDiv + script').get(0).childVar);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parentDiv"></div>

您可以将某些内容显式放入全局范围,以便您可以通过将其添加为全局对象的属性(在浏览器的情况下为window)从其他代码访问它。

在这个例子中注入的 HTML 是:

<section class="mod_el"></section>
<script>
  window.globalVar = {
    foo: 'bar'
  };
</script>

var rawHtmlText = decodeURI(`%3Csection%20class=%22mod_el%22%3E%3C/section%3E%0A%3Cscript%3E%0A%20%20window.globalVar%20=%20%7B%0A%20%20foo:%20'bar'%0A%7D;%0A%3C/script%3E`);

$("#parentDiv").html(rawHtmlText);

console.log(globalVar);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="parentDiv"></div>

【讨论】:

    【解决方案2】:

    您为什么使用 currentScript?正如文档解释 currentScript 返回当前正在处理的元素。我看不出您将如何(或为什么)使用它来获取所需的变量。尝试类似:

    child.html

    <html>
    <body>
        <section class="mod_el">
            <div id="any_element"></div>
        </section>
        <script type="text/javascript">
            var childVar = {
                parameterOne:"ONE"
            };
        </script>
    </body>
    </html>
    

    parent.html(我想你已经包含了 jquery?)

    <!DOCTYPE html>
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta charset="utf-8" />
        <title></title>
        <script
      src="https://code.jquery.com/jquery-3.3.1.min.js"
      integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
      crossorigin="anonymous"></script>
    </head>
    <body>
        <div id="container"></div>
        <script>
            async function LoadChild() {
                const resp = await fetch(`child.html`, {
                    method: "GET",
                    credentials: "include"
                });
                if (!resp.ok)
                    return;
                const result = await resp.text();
                $("#container").html(result);
                console.log(childVar.parameterOne); // should work now
            }
            LoadChild();
        </script>
    </body>
    </html>
    

    【讨论】:

      【解决方案3】:

      我认为您应该使用以下解决方案。它将允许您解析 dom 中的这些脚本,并且您可以轻松地修改 dom 上的任何内容。

      我已将您的 child.html 文件解析为 JS dom 对象,解析脚本元素并附加到您父母的 body 元素中。我知道这需要做一些工作,但您可以解决 child.html 的脚本错误运行时问题。

      Child.html

      <section class="mod_el">
          <h1>Hello</h1>
      </section>
      <script type="text/javascript">
          childVar = {
              parameterOne:"ONE"
          };
      </script>
      

      父.html

      <!DOCTYPE html>
      <html xmlns="http://www.w3.org/1999/xhtml">
      <head>
          <meta charset="utf-8" />
          <title></title>
      </head>
      <body>
          <script>
              async function LoadChild() {
                  const resp = await fetch('child.html', {
                      method: "GET",
                      credentials: "include"
                  });
                  if (!resp.ok)
                      return;
                  const result = await resp.text();
      
                  //Parse html.
                  var parser = new DOMParser();
                  var doc = parser.parseFromString(result,"text/html");
      
                  //Parse scripts.
                  try{
                      var scripts = "";
                      for(var script of doc.getElementsByTagName('script')){
                          scripts += script.innerText;
                      }
                      eval(scripts);
                  }
                  catch(e)
                  {
                      //Manage your runtime child.html script errors here.
                  }
      
                  /*
                  * Append body to our body element.
                  * Here you can amend your child.html's elements.
                  */
                  document.body.appendChild(doc.body);
      
                  console.log(childVar.parameterOne);
              }
              LoadChild();
          </script>
      </body>
      </html>
      

      ? 如果您喜欢这个解决方案,请点赞。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-05-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-01
        • 2023-03-26
        相关资源
        最近更新 更多