javascript - 为什么我的 jQuery .load() 随机失败?
问题描述
我有几个脚本 1) 将 Markdown 文件加载到 div 中,然后 2) 将其转换为 HTML 并将其插入到另一个 div 中。使用 Visual Studio Code 实时预览页面,在保存文件或重新加载页面时,转换后的文本有时会出现,有时不会出现。当我从浏览器(Chrome)手动打开页面或将其拖入其中时,它始终无法出现。转换本身有效,成功地用 HTML 标记替换了标记。问题可能是脚本/行的运行顺序。但是失败似乎是随机的:无论我重新加载页面的速度有多快或慢,它都可能发生。
这是页面代码
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div id="input" style="display: none;"></div>
<script>
$("#input").load("convertme.md");
</script>
<div id="output"></div>
<script src="converter.js"></script>
</body>
这是外部转换脚本(没有.replace
行,仅在本文中省略)
$(document).ready(function() {
input = document.getElementById('input');
output = document.getElementById('output');
function convert(md){
... // this part has the lines that replace the original markups with HTML tags
return md;
};
output.innerHTML = convert(input.innerText);
});
有什么建议吗?
解决方案
.load() 是一个异步函数。因此,您的转换可能是在加载完成之前完成的。您需要在加载函数的完成回调中调用您的转换函数
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="converter.js"></script>
</head>
<body>
<div id="input" style="display: none;"></div>
<div id="output"></div>
</body>
$(document).ready(function() {
let input = document.getElementById('input');
let output = document.getElementById('output');
function convert(md){
... // this part has the lines that replace the original markups with HTML tags
return md;
};
$("#input").load("convertme.md", function()
{
output.innerHTML = convert(input.innerText);
});
});
推荐阅读
- ruby - 我可以自定义蜻蜓 image_uid 吗?
- c++ - 我可以强制 std::vector 留下内存泄漏吗?
- node.js - AWS SES:如何发送大量电子邮件(一次> 10000)
- linux - bash: && 运算符行为
- angular - 服务中的类型不存在属性
- python - 如何将字符串“1:05”转换为时间戳?
- primefaces - 如何防止 minmax spinner 标签允许十进制输入?
- apache-spark - HIVE_CANNOT_OPEN_SPLIT:列
不支持空类型 - laravel - 如何从 laravel 中的集合中读取数据
- angular - 拖动时垫滑块在循环中做出奇怪的反应