首页 > 解决方案 > 为什么我的 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);
});

有什么建议吗?

标签: javascriptjquery

解决方案


.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);    
  });
});

推荐阅读