[英]Multiple Hide/Show Buttons with Javascript
我正在為學校設計一個網站項目。 目前,我正在嘗試創建帶有問題和答案的測驗。 我希望答案被隱藏並通過按鈕顯示。 目前,我正在使用一個腳本,該用戶一旦上傳就“微弱”。
我知道只有一個按鈕有效,因為腳本使用ID而不是類。 我想更改一下,但我不知道如何...大家能幫幫我嗎?
var button_beg = '<button id="button" onclick="showhide()">', button_end = '</button>';
var show_button = 'Show', hide_button = 'Hide';
function showhide() {
var div = document.getElementById( "hide_show" );
var showhide = document.getElementById( "showhide" );
if ( div.style.display !== "none" ) {
div.style.display = "none";
button = show_button;
showhide.innerHTML = button_beg + button + button_end;
} else {
div.style.display = "block";
button = hide_button;
showhide.innerHTML = button_beg + button + button_end;
}
}
function setup_button( status ) {
if ( status == 'Show' ) {
button = hide_button;
} else {
button = show_button;
}
var showhide = document.getElementById( "showhide" );
showhide.innerHTML = button_beg + button + button_end;
}
window.onload = function () {
setup_button( 'hide' );
showhide(); // if setup_button is set to 'show' comment this line
}
var buttons = document.querySelectorAll('.hide-show'); buttons.forEach(function (button) { button.onclick = function () { var content = this.parentNode.getElementsByTagName('span')[0]; if (content.style.display !== 'none') { content.style.display = 'none'; this.textContent = 'show'; } else { content.style.display = 'inline'; this.textContent = 'hide'; } } })
<div> <button class="hide-show">hide</button> <span>Content... 1</span> </div> <div> <button class="hide-show">hide</button> <span>Content... 2</span> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.