我有几个脚本1)加载一个Markdown文件到一个div,然后2)转换成HTML,并插入到另一个div。使用Visual Studio代码实时预览页面时,在保存文件或重新加载页面时,转换后的文本有时会显示,有时不会。当我从浏览器(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);
});有什么建议吗?
发布于 2021-08-28 18:09:58
.load()是一个异步函数。因此,您的转换可能是在加载完成之前完成的。您需要在load函数的finish回调中调用convert函数
<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);
});
});https://stackoverflow.com/questions/68966939
复制相似问题