代码获胜't在$(document).ready中执行,但将在开发人员控制台中执行

Code won't execute in $(document).ready but will in developer console

本文关键字:执行 控制台 开发 ready 获胜 document 代码      更新时间:2023-09-26

我有一些代码封装在$(document).ready(function(){ /*code*/ });中,除了一行代码外,所有代码都运行良好。上面的代码运行良好,下面的代码运行正常,我的控制台中没有任何错误。

$('.main-right.category').height( $('.footer').height() + $('.main-right.category').height() );

那不会着火。但是,如果我将其粘贴到开发人员控制台中,并在页面加载后按enter键,它就可以工作了。所有元素都存在于页面加载时(这意味着没有一个元素是通过javascript动态构建的)。chrome、firefox、IE中的相同结果。

有什么想法吗?

edit:我应该补充一点,我的css是在我的javascript之前加载的,我在同一个javascript文件中做了其他与css相关的调整,效果很好。

此外,如果我在代码行的正上方console.log$('.main-right.category').height()和$('.footer').head(),它们都会像我预期的那样给出非零整数值。

当DOM准备好使用时,ready事件就会触发。它与加载事件不同,后者在所有资产(css、javascript、images…)都已加载时触发。

我想,当你运行代码时,你试图获得高度的元素确实已经计算出了高度,所以看起来什么都没发生。

当您在控制台中执行代码时,所有内容都已加载,因此行为符合预期。

要绑定到加载事件,请检查方法.load().

$(document).ready在DOM结构完全可用时触发,此时通常还没有完成渲染,因此元素的维度可能未知,height()将返回错误的值。

请改用$(window).load()

我通常用设置高度

var height = $('.footer').height() + $('.main-right.category').height();
$('.main-right.category').css('height',height+'px');

您应该使用console来调试选择器并查看元素的高度;

$(document).ready(function() {
  var $footer = $('.footer');
  var $category = ('.main-right.category');
  console.log($category, $footer);
  console.log($category.height(), $footer.height());
  console.log('New height =', ($category.height() + $footer.height()));
});