我正在为学校做一个网站项目。目前我正在尝试创建一个带问题和答案的测验。我希望通过按钮隐藏和显示答案。目前我正在使用一个用户“dimitryous”上传的脚本。
我知道只有一个按钮有效,因为脚本使用的是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
}
答案 0 :(得分: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>