javascript - JavaScript如何等待另一个java脚本首先被解析
问题描述
我遇到了异步 java 脚本的问题。这是我的html
<html>
<head>
<script src="/headScript.js"></script>
</head>
<body>
<div id="inner_id" class="sample"> </div>
...
<script src="/anOtherScript.js"></script>
</body>
</html>
/headScript.js
$(document).ready(function () {
var target=$('#inner_id');
$.ajax({
method: 'GET',
url: '/example',
success: function (result) {
var el= document.createElement('span');
el.id="new_element";
el.setAttribute('name', 'element');
el.setAttribute('content', result);
target.append(el)
}
});
});
/anOtherScript.js
$(document).ready(function () {
console.log($('#new_element));
});
来自标头的脚本创建了新的 div,但似乎这两个脚本正在异步运行,并且在控制台上我得到了未定义。有什么方法可以让 (anOtherScript) 等待第一个先解决?
- 我无法将任何内容更改为 html 文件
- 我能够进行更改的文件是 2 个脚本
解决方案
发生这种情况是因为anOtherScript.js
在您将其加载到 html 之后立即执行 - 这意味着立即执行。但是,您只能在从API#new_element
获得响应后创建元素。example
要解决这个问题:确保 中的代码在 中的代码之后anOtherScript.js
运行headScript.js
。
将所有anOtherScript.js
内容放在一个函数中
const anotherScript = () => {
$(document).ready(function () {
console.log($(`#new_element`))
});
}
然后从文件的success
回调中调用这个函数headScript.js
:
success: function (result) {
var el= document.createElement('span');
el.id="new_element";
el.setAttribute('name', 'element');
el.setAttribute('content', result);
target.append(el)
anotherScript();
}
推荐阅读
- c++ - 错误:'operator<<' 不匹配(操作数类型是 'std::ostream {aka std::basic_ostream
}' 和 '无效') - javascript - 通过其键数组解构对象
- python - 为什么斯坦福 NER 无法识别所有名称?
- c# - 根据简单规则对项目进行分组的算法
- ios - 增加单元格内的 UiImageView 高度时如何增加 tableViewCell 高度?
- keycloak - 我可以在 keycloak 服务器中为 userId 定义自定义格式吗?
- git - IntelliJ IDEA -GIT 的好处?
- c - 如何在变量命名中使用日语字符?
- excel - VBA将某些列复制到特定工作表
- sails.js - 嗨,我对风帆很陌生。任何人都可以帮助我了解如何以及在哪里为 mysql 数据库传递 sql 查询