【发布时间】:2020-09-18 02:20:09
【问题描述】:
我试图了解我对 MediaWiki 用户脚本的basic example 的改编发生了什么。
它以原始形式工作,但是当我在 format_words 函数中将 var 替换为 let 时,它停止工作。我对 JavaScript 和 jQuery 很陌生。这是工作版本:
function format_words(title, numWords){
var text = title+" ("+numWords+" words)";
return text;
}
$(document).ready(function(){
var numWords = $("#mw-content-text > div").text().split(" ").length;
var header = $("#firstHeading").text();
$("#firstHeading").text(format_words(header, numWords));
});
这里是不工作的版本
function format_words(title, numWords){
let text = title+" ("+numWords+" words)";
return text;
}
$(document).ready(function(){
var numWords = $("#mw-content-text > div").text().split(" ").length;
var header = $("#firstHeading").text();
$("#firstHeading").text(format_words(header, numWords));
});
第一个给出了这个 h1 标题:
用户:Wolf/vector.js(74 字)
第二个给出
用户:Wolf/vector.js
我在 MediaWiki 1.31.6 和 MediaWiki 1.35.0-wmf.34 (6ff15fd) 中对此进行了测试,效果相同。
慢慢熟悉 jQuery 之后,我对异步的期望很高,但此时我无法弄清楚它的影响。
反例
当我在本地 HTML+JavaScript(使用热 jQuery)中测试类似代码时,从 var 切换到 let 不会破坏代码。
控制台日志
感谢charlietfl我将脚本更改为
function format_words(title, numWords){
console.log("format_words [enter]");
let text = title+" ("+numWords+" words)";
console.log("format_words: text:"+text);
return text;
}
$(document).ready(function(){
console.log("on ready [enter]");
var numWords = $("#mw-content-text > div").text().split(" ").length;
var header = $("#firstHeading").text();
$("#firstHeading").text(format_words(header, numWords));
console.log("on ready [leave]");
});
... 并打开控制台。对于let 版本,它显示以下错误:
JavaScript parse error: Parse error: Missing ; before statement in file↵
'User:Wolf/vector.js' on line 3 vector.js line 1 > scriptElement:1:8
<anonym> https://some.wiki/w/User:Wolf/vector.js line 1 > scriptElement:1
jQuery 9
DOMEval
globalEval
runScript
fire
add
always
checkCssHandles
execute
implement
<anonym> https://some.wiki/load.php?debug=false&lang=en&modules=user&↵
skin=vector&user=Wolf&version=0hjxbj8:1
我认为 let 不受 JavaScript 支持。很奇怪:我确定 JavaScript 来自浏览器?它适用于我的 Counter 示例。
这是怎么回事?
【问题讨论】:
-
老实说,在这种情况下将
var切换为let或const应该没有任何区别。你确定这是唯一的变化吗? -
当然,我现在正在检查模拟案例两天,所以不仅要仔细检查。我使用了 revert 功能,当我查看差异时(保存前),我得到确认只有这一个词发生了变化。
-
你可以创建 fiddle 或 stackblitz 演示
-
如反例中所述,该问题在 MediaWiki 之外无法重现,所以我猜交付的 HTML 中的某些内容会使浏览器降级为一些古老的 JS。
标签: javascript jquery mediawiki