此代码可以在 Firefox 中完美运行,但不能在 Chrome 中运行。
我正在使用带有 Chrome 的网络服务器,因此 .load()
工作正常。
$(function(){
$("#header").load("header.html");
});
$(document).ready(function(){
$('#notif').text("5");
}
当我使用 chrome 进行调试时,代码执行正常,但 <span id="notif"></span>
中没有插入任何内容。 .
<span id="notif"></span>
那是我的header.html
使用 JS 动态加载。
同样,它在 Firefox 中运行良好,但在 Chrome 中则不然。
最佳答案
加载是异步的,因此文档将在加载结束之前准备好(并已触发)。 简而言之,当文档准备好时 $('#notif') 不存在,因为它尚未加载。
$(function(){
$("#header").load("header.html",function(){
$('#notif').text('5');
});
});
不是第二个参数,匿名函数,加载成功完成后会启动。
Firefox 和 Chrome 之间的差异可能与下载速度有关,但我不能 100% 确定。需要更多测试。
sometimes (especially IE) debugging the code via a breakpoint, may cause enough delay to the document.ready trigger to have finished loading. So no "faults" are discovered.
关于javascript - 代码在 Firefox 中有效,但在 Chrome 中无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45381885/