У меня есть этот простой слайд jquery, который я хочу иметь только одну кнопку. Если div отображается, кнопка show станет кнопкой hide. И если div скрыт, кнопка hide станет кнопкой show.
В настоящее время у меня есть отдельная кнопка show и hide. Я не знаю, как объединить эти кнопки в один. Надеюсь, кто-то здесь может мне помочь. :(
<script type="text/javascript"
src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript"
src="http://code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#hide").click(function(){
$(".target").hide( "slide",
{ direction: "up" }, 500 );
});
$("#show").click(function(){
$(".target").show( "slide",
{direction: "up" }, 500 );
});
});
</script>
<style>
div{ width:100%;
height:100px;
background: #000;
color: #fff;
}
</style>
</head>
<div class="target" style="display:none;">
My Bag Items
<button id="hide">Hide My Bag</button>
</div>
<button id="show">My Bag</button>
$("#toggle").click(function(){
var $target = $('.target'),
$toggle = $(this);
$target.slideToggle( 500, function () {
$toggle.text(($target.is(':visible') ? 'Hide' : 'Show') + ' My Bag');
});
});
Новая разметка -
<div class="target">My Bag Items</div>
<button id="togButton">Hide</button>
JQuery
$('#togButton').click(function() {
$('.target').slideToggle(500);
if( $(this).text() == 'Hide' ) {
$(this).text('Show');
} else {
$(this).text('Hide');
}
});
$(this)
как var $this = $(this);
чтобы избежать избыточных поисков и обхода DOM. Каждый раз, когда вы обнаруживаете, что используете функцию $('someSelector')
более одного раза, $('someSelector')
ее. Приветствия ~