gpt4 book ai didi

javascript - try...catch 语句在 IE 中到底如何工作?

转载 作者:行者123 更新时间:2023-12-01 03:56:35 25 4
gpt4 key购买 nike

我在这个函数中有一个foreach()循环,通过搜索互联网我知道,foreach循环在IE中不起作用。为了节省时间,我简单地在它周围添加了一个:try {} catch {},但 IE 仍然通过函数调用提醒我存在错误。

为什么 IE 11 可以工作? 代码:

代码:

function classAndIdSpy() {

var req = new XMLHttpRequest();
var x = document.getElementsByClassName("spy");
var page_you_on = window.location.href.split("/");
var json56 = '{ "div_ids_classes" : [{"PAGE":"'+page_you_on[page_you_on.length-1]+'"},';

try {
// Block of code to try.
for(var xy of x) {

json56 += '{"SPY_ID":"'+xy.id+'","CLASS":"'+xy.parentNode.className+'","ID":"'+xy.parentNode.id +'"}';

json56 += (x.length-1 > [].indexOf.call(x, xy)) ? ',' : '';

}
json56 += ']}';

req.open('POST', '../admin/id_class_colect.php', true);
req.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
req.send("json2="+json56);

var status;
req.onreadystatechange = function() {//Call a function when the state changes.
if(req.readyState == 4 && req.status == 200) {
status = req.responseText;
console.log("Send ajax. Colected Id and Class information of content DIVs into database. Status:"+status);
}}
}
catch(err) {
console.log("Your browser doesn't support ID and Class information of content DIV into database. Please use another browser.");
return false;
}
} //End of ClassAndIDspy

我在控制台中收到以下错误:SCRIPT1004: Expected ';' (该函数在Firefox中运行良好,我认为没有缺少分号)

而且,这是我希望 Internet Exporer 忽略的部分:代码:

for(var xy of x) { 

json56 += '{"SPY_ID":"'+xy.id+'","CLASS":"'+xy.parentNode.className+'","ID":"'+xy.parentNode.id +'"}';

json56 += (x.length-1 > [].indexOf.call(x, xy)) ? ',' : '';

}

感谢您的帮助!

最佳答案

您似乎误解了 try-catch 的要点。

trycatch 用于处理 JavaScript 代码运行时出现的异常。您的代码无法在 IE 中运行,因为它无法编译。 trycatch 对编译失败无能为力。

据我所知,您的选择是:

  • 使用 Babel 或其他转译器将现代 JS 代码转换为可在 IE 中运行的 JS 代码。
  • 使用“普通”for 循环而不是 for (xy of x) 循环。这样做并不需要太多的努力,正如我在评论中指出的那样,您的 for 循环无论如何都使用数组中元素的索引。

我强烈建议您放弃让 IE 忽略代码块的想法。

关于javascript - try...catch 语句在 IE 中到底如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42612759/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com