![](/img/trans.png)
[英]Improve JavaScript - jQuery code for active menu and show/hide div
[英]javascript/Jquery improvement on a .hide() .show() div menu
我是javascript和jquery自我思考的超級新手.... been在此菜單上工作了一段時間,我終於“完成了”,但是iv得到了一些可怕的代碼,我正在尋找方法來改進我的代碼以使其更具可讀性以及功能方面的任何提示和提示都會有所幫助。 節省頁面空間的想法是,每個div都會有表單的不同部分,用戶將在此處填寫一些代碼
<body>
<div class="content">
<div class="menu" id="menu"></div>
<div class="content" id="sort"></div>
<div class="menu"id="menu1"></div>
<div class="content" id="1sort"></div>
<div class="menu"id="menu2"></div>
<div class="content" id="sort2"></div>
</div>
<script>
var show = true;
var show2 = false;
var show3 = false;
$('#1sort').hide("fast");
$('#sort2').hide("fast");
$("#menu").click(function () {
if (show == true) {
$('#sort').hide("fast");
$('#1sort').show("fast");
show = false;
show2 = true;
} else if (show == false) {
$('#sort').show("fast");
$('#1sort').hide("fast");
$('#sort2').hide("fast");
show = true;
show2 = false;
show3 = false;
}
});
$("#menu1").click(function () {
if (show2 == true) {
$('#1sort').hide("fast");
$('#sort2').show("fast");
show2 = false;
show3 = true;
} else if (show2 == false) {
$('#1sort').show("fast");
$('#sort').hide("fast");
$('#sort2').hide("fast");
show = false;
show2 = true;
show3 = false;
}
});
$("#menu2").click(function () {
if (show3 == false) {
$('#1sort').hide("fast");
$('#sort').hide("fast");
$('#sort2').show("fast");
show = false;
show2 = false;
show3 = true;
}
});
</script>
這里有用的技術是在鏈接上裝飾一些額外的屬性(最好是html5 data-*
),以指示其相關內容是什么。
<div class="menu" id="menu" data-content="sort"></div>
<div class="content" id="sort"></div>
<div class="menu"id="menu1" data-content="1sort"></div>
<div class="content" id="1sort"></div>
<div class="menu" id="menu2" data-content="sort2"></div>
<div class="content" id="sort2"></div>
然后,您可以在單擊某項以隱藏當前可見的項並顯示所需的項時使用它:
$('.menu').click(function(){
$('.content:visible').hide('fast');
$('#' + $(this).data('content')).show('fast');
});
實時示例: http : //jsfiddle.net/hAbPa/
您可以使用一些基本的遍歷函數和.is
來確定可見性。 您不需要布爾變量也不需要元素ID: http : //jsfiddle.net/K2sqy/2/ 。
$(".menu").click(function() {
var $next = $(this).next(".content"); // corresponding .content element
var isVisible = $next.is(":visible"); // is it currently visible?
$(this).siblings(".content").hide("fast"); // hide all siblings
$next[isVisible ? "hide" : "show"]("fast"); // toggle the corresponding .content
if(isVisible) {
// it was visible, so now it's hidden. Show the other .content:
// the next or, if not available, the previous
var $second = $next.nextAll(".content").first();
if($second.length === 0) {
$second = $next.prevAll(".content").first();
}
$second.show("fast");
}
});
您可能還考慮使用jquery .toggle()。 更多信息在這里。
$('#foo').toggle(showOrHide);
is equivalent to:
if ( showOrHide == true ) {
$('#foo').show();
} else if ( showOrHide == false ) {
$('#foo').hide();
}
我不確定100%(未測試)...但是我認為這非常接近。
$(".menu").click(function (){
$(this).next('.content').toggle();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.