2016-10-23 7 views
0

私は学校のウェブサイトプロジェクトに取り組んでいます。現在、私は質疑応答でクイズを作成しようとしています。答えを隠してボタンで表示したい。現時点では、私はスクリプトを使用しています。複数の非表示/表示ボタンとJavaScriptを使用

私はスクリプトがidsでクラスを使用していないため、ボタンが1つしかないことはわかっています。私はそれを変更したいと思いますが、私はどのように考えていない...あなたは私を助けてくれますか?

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 
} 

答えて

1

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>

+0

これは、 "ファイル名を指定して実行コードスニペット" ではなく私のウェブサイトで動作します。さらに、コンテンツは読み込み時に非表示にする必要があります。 – Timonswh

関連する問題