我正在嘗試構建我網站的一部分,其中 2 個不同的按鈕打開 2 條不同的訊息。但是,當我運行代碼時,當我按下第二個按鈕時內容不會改變。
我對 JQuery 不是非常熟練,所以我不確定到底出了什么問題。
這是我的代碼:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btnClick">Section one</button>
<button id="btnClick2">Section two</button>
<div id="1">
<p>Section one. Message one.</p>
</div>
<div id="2" style="display:none;">
<p>Section one. Message two.</p>
</div>
<div id="3" style="display:none;">
<p>Section two. Message one.</p>
</div>
<div id="4" style="display:none;">
<p>Section two. Message two.</p>
</div>
$('#btnClick').on('click', function () {
if ($('#1').css('display') != 'none') {
$('#2').show().siblings('div').hide();
} else if ($('#2').css('display') != 'none') {
$('#1').show().siblings('div').hide();
} else {
$('#1').show().siblings('div').hide();
}
});
$('#btnClick2').on('click', function () {
if ($('#3').css('display') != 'none') {
$('#4').show().siblings('div').hide();
} else if ($('#4').css('display') != 'none') {
$('#3').show().siblings('div').hide();
} else {
$('#3').show().siblings('div').hide();;
}
});
uj5u.com熱心網友回復:
我沒有像您嘗試使用多個功能,而是使用一個主功能編輯了您的代碼。該函式讀取data-attribute顯示或隱藏 div,例如:
const sections = $('.container-section');
$('.btnClick').on('click', function() {
$(sections).find('[data-target]').hide();
$(sections).find('[data-target="' $(this).data('section') '"]').show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="btnClick" data-section="1">Section one</button>
<button class="btnClick" data-section="2">Section two</button>
<div class="container-section">
<div data-target="1">
<p>Section one. Message one.</p>
</div>
<div data-target="2" style="display:none;">
<p>Section one. Message two.</p>
</div>
</div>
參考:
- 使用資料屬性
- 。節目()
- 。隱藏()
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/532208.html
