jQuery onLoad问题
你能解释一下为什么这个片段有效而无效吗jQuery onLoad问题,jquery,domdocument,onload,Jquery,Domdocument,Onload,你能解释一下为什么这个片段有效而无效吗 $('#about, #subscribe, #contact').hide(); $('.home').click(function() { var id = $(this).html().toLowerCase(); var $content = $('#' + id + ':not(:visible)'); if ($('.current').length === 0) { showContent($cont
$('#about, #subscribe, #contact').hide();
$('.home').click(function() {
var id = $(this).html().toLowerCase();
var $content = $('#' + id + ':not(:visible)');
if ($('.current').length === 0) {
showContent($content)
}
else {
$('.current').fadeOut(600, function() {
showContent($content)
});
}
});
function showContent(content) {
content.fadeIn(600);
$('.current').removeClass('current');
content.addClass('current');
}
我将完全相同的代码放在小提琴中。将代码包装在:
$(document).ready(function(){
// your code here
});
这意味着您的代码只会在DOM初始化后运行。现在,您的代码将在DOM准备好被操作之前运行,这将导致您遇到的问题
在fiddles中,代码会自动加载运行(请参见链接到的fiddle中的onLoad
)
请在此处详细阅读:这是因为您没有在
$(window.load({})中包装代码代码>就像你在小提琴中指定的那样
$(window).load(function() {
$('#about, #subscribe, #contact').hide();
$('.home').click(function() {
var id = $(this).html().toLowerCase();
var $content = $('#' + id + ':not(:visible)');
if ($('.current').length === 0) {
showContent($content)
}
else {
$('.current').fadeOut(600, function() {
showContent($content)
});
}
});
function showContent(content) {
content.fadeIn(600);
$('.current').removeClass('current');
content.addClass('current');
}
});