[英]How can I show and hide different <section> of my html page using jquery?
[英]How can I Compress My .show and .hide jQuery?
我是jQuery的新手,我知道必須有越來越少的代碼才能做到這一點。 所以,我這里有兩個div。 第一名將在不同的div中顯示一個班級。 用戶完成操作后,“ div 2”將隱藏此元素,然后單擊“ div 2”。 我覺得我的jQuery代碼太長了。 這是我的JSFIDDLE。 https://jsfiddle.net/g812sqry/
<div class="container">
<div>
<p id="one">Div One</p>
</div>
<div>
<p id="two">Div Two</p>
</div>
</div>
#one {
width:60px;
background-color:green;
padding:10px;
cursor:pointer;
}
#two {
width:60px;
background-color:green;
padding:10px;
display:none;
cursor:pointer;
}
$(document).ready(function () {
$('#one').click(function () {
$(this).hide();
});
$('#one').click(function () {
$('#two').show();
});
$('#two').click(function () {
$(this).hide();
});
$('#two').click(function () {
$('#one').show();
});
});
嘗試使用.toggle()
$(document).ready(function () {
var elems = $("#one, #two");
elems.click(function () {
elems.toggle()
});
})
jsfiddle https://jsfiddle.net/g812sqry/4/
您可以合並兩個選擇器的單擊事件。
$(document).ready(function () {
$('#one, #two').click(function () {
$('p').show();
$(this).hide();
});
});
這樣更好。
$(document).ready(function () {
$('#one').click(function () {
$(this).hide();
$('#two').show();
});
$('#two').click(function () {
$(this).hide();
$('#one').show();
});
});
您已經在調用$('#divID').click()
函數,而無需再次為#one
和#two
DIV調用它
$(document).ready(function () { $('#one').click(function () { $(this).hide(); $('#two').show(); }); $('#two').click(function () { $(this).hide(); $('#one').show(); }); });
#one { width:60px; background-color:green; padding:10px; cursor:pointer; } #two { width:60px; background-color:green; padding:10px; display:none; cursor:pointer; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="container"> <div> <p id="one">Div One</p> </div> <div> <p id="two">Div Two</p> </div> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.