我的 jQuery 代码在单击按钮时将一个类添加到一个元素。仅当我将代码传递给 $(document).ready()
时,该代码才有效。这同样适用于 Javascript,只有当我使用 window.onload
时代码才能正常工作。这种行为的原因是什么?我的 .js 文件位于 HTML 的“head”部分,它已在浏览器呈现 HTML 页面时被读取。
$('#switcher-large').on('click', function(){
$('#content').addClass('large');
});
var docId = document.getElementById('switcher-large');
docId.onclick = function(){
var content = document.getElementById('content').classList.add('large');
}
工作代码:
$(document).ready(function(){
$('#switcher-large').on('click', function(){
$('#content').addClass('large');
});
});
window.onload = function(){
var docId = document.getElementById('switcher-large');
docId.onclick = function(){
var content = document.getElementById('content').classList.add('large');
}
}
最佳答案
在文档为 ready
之前,无法安全地操作 HTML 页面.您已添加 js
文档开头的标签,在 <head>
中甚至在 <body>
之前是写的。所以,如果你正在操纵来自 <body>
的东西内容,它在执行时不存在。现在内容在$(document).ready(function(){}
下当整个 HTML 文档准备就绪并且所有元素都出现在文档中时执行。所以当你使用::
$('#switcher-large').on('click', function(){
$('#content').addClass('large');
});
它将执行 before
你按钮 ID #switcher-large
加载到文档中。
关于javascript - 使用 jQuery/Javascript 的 DOM 事件仅适用于 $().ready 或 window.onload,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50433294/