You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript开源拼写检查库Typo.js使用报错问题求助

问题原因
  • 时序错误:配置dictionaryPath参数让Typo自动加载字典时,字典文件通过异步请求拉取,你在实例化Typo后立刻调用checkWord(),此时字典文件还未加载完成,dictionary实例未初始化完成,调用.check()方法直接报错。
  • 你代码中注释掉的手动加载字典逻辑本身可用,但整段被注释后,没有任何等待字典加载完成的逻辑就直接执行拼写检查。
  • 环境坑:如果直接双击本地HTML文件通过file://协议打开,浏览器会拦截本地文件的异步请求,导致字典加载失败,必须将项目部署在本地HTTP服务上访问。
修复方法

直接在初始化Typo时增加loaded回调,等字典完全加载完成后再执行拼写检查、显示交互表单,修改后的完整可运行代码如下:

<!doctype html>
<html>
<head>
    <title>Typo.js Example</title>
    <meta charset="UTF-8" />
    <script type="text/javascript" src="typo/typo.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
    <script type="text/javascript">
        // 配置加载完成回调,字典就绪后再执行业务逻辑
        var dictionary = new Typo("en_US", false, false, {
            dictionaryPath: "typo/dictionaries",
            loaded: function() {
                checkWord('mispelled');
                $('#word-form').show();
            }
        });

        function checkWord(word) {
            var wordForm = $('#word-form');
            wordForm.hide();

            var resultsContainer = $('#results');
            resultsContainer.html('');

            resultsContainer.append($('<p>').text("Is '" + word + "' spelled correctly?"));

            var is_spelled_correctly = dictionary.check(word);

            resultsContainer.append($('<p>').append($('<code>').text(is_spelled_correctly ? 'yes' : 'no')));

            if (!is_spelled_correctly) {
                resultsContainer.append($('<p>').text("Finding spelling suggestions for '" + word + "'..."));

                var array_of_suggestions = dictionary.suggest(word);
                resultsContainer.append($('<p>').append($('<code>').text(array_of_suggestions.join(', '))));
            }

            wordForm.show();
        }
    </script>
</head>
<body>
    <h1>Typo.js Demo</h1>
    <p>This page is an example of how you could use Typo.js in a webpage if you need spellchecking beyond what the OS provides.</p>
    <p id="loading-progress"></p>
    <div id="results"></div>
    <!-- 初始隐藏表单,字典加载完成后再展示,避免提前操作报错 -->
    <form method="GET" action="" onsubmit="checkWord( document.getElementById( 'word' ).value ); return false;"
        id="word-form" style="display: none;">
        <p>Try another word:</p>
        <input type="text" id="word" value="mispelled" />
        <input type="submit" value="Spellcheck" />
    </form>
</body>
</html>
前置校验项
  • 确认目录结构和路径配置一致:typo/typo.js文件存在,且typo/dictionaries/en_US/目录下已经放好en_US.aff、en_US.dic两个官方字典文件,路径拼写无错误。
  • 必须通过本地HTTP服务(如VS Code Live Server、Nginx、Python内置http服务等)访问页面,不要直接双击打开本地HTML文件,避免跨域拦截导致字典加载失败。

内容的提问来源于stack exchange,提问作者Ashok BK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.28 16:15:54