简体   繁体   English

将Javascript代码从html移至外部js文件后,为什么为什么不起作用?

[英]Why won't Javascript code work after moving it from html to an external js file?

I have this Javascript code that was working perfectly fine in my HTML. 我有此Javascript代码,在我的HTML中效果很好。 When I moved it to my main.js it suddenly stopped working. 当我将其移至main.js时,它突然停止工作。

Disclaimer: I am very new to jQuery and Javascript, so sorry if it is really obvious. 免责声明:我对jQuery和Javascript非常陌生,如果真的很抱歉,请对不起。

var infoVisible = false,
buyVisible = false;

function closeAllProductInfo() {
    $('#info').css({visibility: 'hidden'});
    $('#buy').css({visibility: 'hidden'});
    $('#options.info a').removeClass('active');
    $('#options.buy a').removeClass('active');
    infoVisible = false;
    buyVisible = false;
    imagesVisible = false;
}

function openProductInfo() {
    closeAllProductInfo();
    $('#info').css({visibility: 'visible', opacity: 0});
    $('#info').animate({opacity: 1}, 250);
    $('#options.info a').addClass('active');
    infoVisible = true;
}

function openProductBuy() {
    closeAllProductInfo();
    $('#buy').css({visibility: 'visible', opacity: 0});
    $('#buy').animate({opacity: 1}, 250);
    $('#options.buy a').addClass('active');
    buyVisible = true;
}

$('.info').click(function() {
    if (infoVisible) { 
        $('#info').animate({opacity: 0}, 250, function() {  
            closeAllProductInfo(); 
        }); 
    } else { 
        openProductInfo(); 
    }

    return false;
});

$('.buy').click(function() {
    if (!$(this).hasClass('in-active')) {
        if (buyVisible) { 
            $('#buy').animate({opacity: 0}, 250, function() { 
                closeAllProductInfo(); 
            }); 
        } 
        else { 
            openProductBuy(); 
        }
    }

    return false;
});

$('#info').click(function() {
    if (infoVisible) { 
        $('#info').animate({opacity:0}, 250, function() { 
            closeAllProductInfo(); 
        }); 
    }
});

$('#buy').click(function() {
    if (!$(this).hasClass('in-active')) {
        if (buyVisible) { 
            $('#buy').animate({opacity:0}, 250, function() { 
                closeAllProductInfo(); 
            }); 
        }
    }
});

Probably because it used to execute after the document was loaded but now it executes when the script is loaded. 可能是因为它曾经在文档加载后执行,但是现在它在脚本加载时执行。 Do you load main.js at the end of your HTML file or the start? 您是在HTML文件的末尾还是开始时加载main.js? Use this to get it to execute after the document is ready: 准备好文档后,可以使用它来执行:

jQuery(document).ready(function($) {
  // Code using $ as usual goes here.
});

Try to wrap all your code in : 尝试将所有代码包装在中:

$(document).ready(function(){
   // Your code in here.
}); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM