[英]JS Multiple $(document).ready(function() Merging Issue:
有两个主要的JS脚本。 两者均按预期独立工作。 其中一个用于菜单(当前不在HTML中),另一个用于将动态更改的div(在HTML以下)。 这两个都使用$(document).ready(function ()
当我将它们放在单独的文件中时它们不起作用。将所有功能放在相同的$(document).ready(function ()
下仍然不起作用。如果我将它们放在同一文件中,就像两个独立的脚本一样,只有最顶层的脚本才能按预期工作,有什么想法吗?我是JS的新手,我正在努力弄清代码的布局方式。
JS:
(function ($) {
"use strict";
var mainApp = {
main_fun: function () {
$('#main-menu').metisMenu();
$(window).bind("load resize", function () {
if ($(this).width() < 768) {
$('div.sidebar-collapse').addClass('collapse')
} else {
$('div.sidebar-collapse').removeClass('collapse')
}
});
},
initialization: function () {
mainApp.main_fun();
}
}
$(document).ready(function () {
mainApp.main_fun();
});
}(jQuery));
第二个JS
$(document).ready(function(){
var $content = $('.menu-content');
function showContent(type) {
$($content).hide();
$('#'+type).show();
}
$('.menu').on('click', '.menu-btn', function(e) {
showContent(e.currentTarget.hash.slice(1));
e.preventDefault();
});
showContent('about');
});
HTML:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script src= "http://code.jquery.com/jquery-1.10.2.min.js" type="text/javascript"></script>
<script src="{{ url_for('static',filename='js/menu/custom.js') }}"></script>
<style>
div{
height: 200px;
width: 50%;
background-color: powderblue;
}
</style>
</head>
<body>
<ul class="menu">
<li><a href="#about" class="menu-btn">About</a></li>
<li><a href="#contact" class="menu-btn">Contact</a></li>
<li><a href="#cluster" class="menu-btn">cluster</a></li>
</ul>
<div id="about" class="menu-content">This is static - About</div>
<div id="contact" class="menu-content">This is static - Contact</div>
<div id="cluster" class="menu-content">cluster</div>
</body>
</html>
这可能是合并的代码,请尝试以下方法:
$(document).ready(function(){
var $content = $('.menu-content');
function showContent(type) {
$($content).hide();
$('#'+type).show();
}
$('.menu').on('click', '.menu-btn', function(e) {
showContent(e.currentTarget.hash.slice(1));
e.preventDefault();
});
showContent('about');
mainApp.main_fun();
});
(function ($) {
"use strict";
var mainApp = {
main_fun: function () {
$('#main-menu').metisMenu();
$(window).bind("load resize", function () {
if ($(this).width() < 768) {
$('div.sidebar-collapse').addClass('collapse')
} else {
$('div.sidebar-collapse').removeClass('collapse')
}
});
},
initialization: function () {
mainApp.main_fun();
}
}
} (jQuery));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.