我在这个函数中有一个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:预期的";"(该功能在Firefox中运行良好,我认为没有缺少分号)
而且,这是我希望互联网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
.
try
和catch
用于处理 JavaScript 代码运行时出现的异常。 您的代码无法在 IE 中运行,因为它无法编译。 对于编译失败,try
和catch
无能为力。
在我看来,您的选择是:
- 使用 Babel 或其他一些转译器将现代 JS 代码转换为将在 IE 中运行的 JS 代码。
- 使用"普通"
for
循环而不是for (xy of x)
循环。 这样做不需要付出很多努力,正如我在评论中指出的那样,您的for
循环无论如何都在使用数组中元素的索引。
我强烈建议你放弃让IE忽略代码块的想法。