我想在我的 JavaScript 代码中提供条件方法。此代码在 Internet Explorer 10 版本中不起作用。当我将此代码粘贴到 JavaScript validator 时,将显示此消息:
Function declarations should not be placed in blocks. Use a function expression or move the statement to the top of the outer function.
我怎样才能在这里有一个功能?
if(jQuery("header").attr("id") == "header-style-two")
{
function sticky_relocate() {
var window_top = jQuery(window).scrollTop();
var div_top = jQuery('#sticky-anchor').offset().top;
if (window_top > div_top) {
jQuery('.mainmenu-area').removeClass('light-menu');
//This is for when div in top
} else {
jQuery('.mainmenu-area').addClass('light-menu');
//This is for when div in not top
}
}
jQuery(function () {
jQuery(window).scroll(sticky_relocate);
sticky_relocate();
});
}
最佳答案
You can't have named function in an if block (根据规范它是无效的,无论如何提升都会让它变得相当困惑,但一些 JavaScript 引擎可能会尝试补偿错误的代码,这就是它可能在某些浏览器中工作的原因),但你可以将函数分配给 if 中的变量 block 。
而不是:
function sticky_relocate() {
你可以这样做:
var sticky_relocate = function() {
所以像这样的东西就可以了:
if(jQuery("header").attr("id") == "header-style-two")
{
var sticky_relocate = function() {
var window_top = jQuery(window).scrollTop();
var div_top = jQuery('#sticky-anchor').offset().top;
if (window_top > div_top) {
jQuery('.mainmenu-area').removeClass('light-menu');
//This is for when div in top
} else {
jQuery('.mainmenu-area').addClass('light-menu');
//This is for when div in not top
}
}
jQuery(function () {
jQuery(window).scroll(sticky_relocate);
sticky_relocate();
});
}
关于javascript - 如何使用 JavaScript 代码在 if 条件下使用函数方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41217351/