javascript - 使用 jQuery/Javascript 的 DOM 事件仅适用于 $().ready 或 window.onload

标签 javascript jquery dom event-handling jquery-events

我的 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/

相关文章:

使用自定义属性进行 Javascript 切换

javascript - 没有jquery的无限滚动?

javascript - 我想将列表项显示为 2 列或更多列(动态对齐)

javascript - Jquery/Javascript 为一类四个按钮提供四个不同的随机数

DOM 中的 Javascript 函数为 SVG 生成点击事件

javascript - HTML/JS : Required input X ignored if input Y is filled

javascript - Processing.js 不会加载脚本

javascript - ReactJS - 单击时容器 div 的访问键?

php - Jquery 序列化并传入其他自定义发布数据

javascript - 需要帮助在 Javascript 中查找/遍历 dom