我如何在脚本中定义tracery来生成随机句子?



在努力从存储在我的网站托管的服务器中的独立跟踪库获取数据后,我决定使用以下代码的另一种方法,但它是不成功的,因为我无法生成所需的结果,这只是一个随机的句子,每次我加载页面:

<html>
<head>
<script defer src="js/tracery/tracery.js"></script>
<script defer src="js/tracery/tracery.min.js"></script>
<script defer src="js/tracery/jquery-1.11.2.min.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head>
<script>
var data = {
"origin": "#salutation#, #name#",
"salutation": ["Hi", "Good morning", "Good evening", "Good night"],
"name": ["John", "Mary", "Peter", "Anne"]
};
var grammar = tracery.createGrammar(data);
var sentence = grammar.flatten("#origin#");
document.getElementById("output").innerHTML = sentence;
</script>
<body>
<div id="output"></div>
</body>
</html>

我在浏览器的控制台上得到以下错误:"消息7 Uncaught ReferenceError: tracery is not defined at agronobot.html:17:15"。

我调用了所有这些文件,但我认为我唯一需要的是tracery.min.js,控制台显示tracery已完成,但正如我之前所说,当我加载页面时,我无法看到期望的结果。

要修复这个错误,只需将<script>库放入<head>标记中,并确保先导入jquery库。

编辑:代替导入本地tracery.js,您可以尝试导入在线版本:
https://tracery.io/editor/js/tracery/tracery.js

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.4/jquery.min.js"></script>
<script src="https://tracery.io/editor/js/tracery/tracery.js"></script>
</head>
<body>
<div id="output"></div>
<script>
var data = {
"origin": "#salutation#, #name#",
"salutation": ["Hi", "Good morning", "Good evening", "Good night"],
"name": ["John", "Mary", "Peter", "Anne"]
};
var grammar = tracery.createGrammar(data);
var sentence = grammar.flatten("#origin#");
document.getElementById("output").innerHTML = sentence;
</script>
</body>
</html>

相关内容

  • 没有找到相关文章

最新更新