gpt4 book ai didi

如果元素不在页面上,则 JavaScript 错误

转载 作者:行者123 更新时间:2023-11-28 01:18:17 24 4
gpt4 key购买 nike

我希望每个页面都有一个脚本文件,其中包含该特定页面可能需要或不需要的脚本。在我的主页上有这个脚本:

$(function () { 

var $select = $('#select');
var $window = $(window);
var isFixed = false;
var init = $('#select').offset().top;

$window.scroll(function () {
var currentScrollTop = $window.scrollTop();
if (currentScrollTop > init && isFixed === false) {
isFixed = true;
$select.css({
top: 0,
position: 'fixed'
});
console.log("fixed");
} else if(currentScrollTop <= init && isFixed === true) {
isFixed = false;
$select.css('position', 'relative');
console.log("unfixed");
}
});

$("#scroll").click(function () {
$('html, body').animate({
scrollTop: $(".jumbo").offset().top + $(".jumbo").height()
}, 300);
});

});

但是,当它在主页(没有 #select 元素)上运行时,我收到此错误并破坏了我的脚本:

Uncaught TypeError: Cannot read property 'top' of undefined

如果该特定页面不需要该脚本,而无需将其加载到自己的文件中,如何才能使其不导致错误?

我应该让它在页面加载时调用该函数吗?

最佳答案

您可以使用length属性来检查元素是否存在:

var init = $select.length ? $select.offset().top : 0;

如果该元素不存在,则返回 0,否则返回其顶部偏移量。

关于如果元素不在页面上,则 JavaScript 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23561532/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com