Chrome 提前更改 HTML ID

Chrome changing HTML ID in advance

本文关键字:HTML ID Chrome      更新时间:2023-09-26

我正在使用javascript更改HTML图像的Id,但我注意到chrome正在读取前面的代码,并提前更改Id。当我在 IE 上运行完全相同的代码,甚至在 chrome 上使用 f12 deveolper 工具使代码逐行运行时,控制台记录的内容与我简单地在 chrome 上运行它时不同。

console.log(document.getElementById("apples"));//IE logs html element with Id of apples, chrome logs element with id of oranges 
document.getElementById("imageId1").id = "oranges";//Change ID to oranges
console.log(document.getElementById("oranges"));//Both IE and Chrome log html element with Id of oranges

因此,如果 Chrome 我怀疑的那样提前阅读,并且提前更改 ID,我该如何让它停止(因为它弄乱了我的代码)。

Chrome的控制台显示该元素的实时日志。这就是为什么你看到的是橙子而不是苹果

改用console.dir,您将看到 id(日志记录时的值)印在元素名称旁边。但是,如果您打开对象属性,您将看到id的实时值。

console.dir(document.getElementById("apples"));
document.getElementById("apples").id = "oranges";
console.dir(document.getElementById("oranges"));
<img id="apples" />

或者将最后两个语句放在一个 setTimeout 中

console.log(document.getElementById("apples"));
//gives chrome the time to log the element
setTimeout(function(){
    document.getElementById("apples").id = "oranges";
    console.log(document.getElementById("oranges"));
},100);
<img id="apples" />

您也可以只记录属性本身而不是对象

console.log(document.getElementById("apples").id);
document.getElementById("apples").id = "oranges";
console.log(document.getElementById("oranges").id);
<img id="apples" />