【发布时间】: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