MathJax.Hub.Register.StartupHook("End", function() {
var classes = ["45e5d940-d015-4074-a934-f51ab8d6056a", "26ccb022-d472-4466-8c63-801e549ffcf2", "c4ecd641-e4e1-40a0-9560-fd4dc4d299b6", "d5d15822-f90d-4686-b816-77d8d4f28cc91Left", "d5d15822-f90d-4686-b816-77d8d4f28cc92Right", "a25b8ba9-03de-4068-b587-2b3c85380c591Left", "a25b8ba9-03de-4068-b587-2b3c85380c592Left", "a25b8ba9-03de-4068-b587-2b3c85380c593Right", "dd080c5f-3c94-4c04-bf59-68b03c8b75231Left", "dd080c5f-3c94-4c04-bf59-68b03c8b75232Left", "dd080c5f-3c94-4c04-bf59-68b03c8b75233Right", "d975febc-0e4f-46cc-b427-7989a2cbb0cb1Left", "d975febc-0e4f-46cc-b427-7989a2cbb0cb2Left", "d975febc-0e4f-46cc-b427-7989a2cbb0cb3Right", "32d6ac0d-6201-4045-8aca-a7cd086dd96a1Left", "32d6ac0d-6201-4045-8aca-a7cd086dd96a2Left", "32d6ac0d-6201-4045-8aca-a7cd086dd96a3Right", "1e89393b-8ff4-40c6-855b-812b7ee6f1ed1Left", "1e89393b-8ff4-40c6-855b-812b7ee6f1ed2Left", "1e89393b-8ff4-40c6-855b-812b7ee6f1ed3Right"];
for (var i = 0; i < classes.length; i++) {
console.log(i); // this prints correctly every loop
console.log(classes[i]); // this prints correctly every loop
console.log(document.getElementById(classes[i] + "_event")); // this finds it correctly
var c = classes[i];
document.getElementById(c + "_event").addEventListener("mouseover", function() {
var classList = document.getElementsByClassName(c);
console.log(c); // prints the last item in the classes list every time -- bug
console.log(classList);
Array.from(classList).forEach(function(e) {
if (e["style"]) {
e.style["color"] = "red";
}
});
});
}
});
此代码存在范围问题。 变量'c'是在for循环中定义的,它引用循环中该项的索引。
我可以正确地连接事件,但是从事件中调用的函数将c变量定义为被调用时列表中的最后一项。
如果将c替换为class [i],它将打印未定义的内容(在函数中)