在 hides/shows 所有元素 class 的函数中单击更改按钮内部文本

Change button inner text on click in a function that hides/shows all elements with class

找到了 show/hide 所有具有 class 的元素的方法,但我需要将单击时的按钮文本从隐藏更改为显示,然后再从显示更改为隐藏。到目前为止,这是我的 JS 代码:

document.getElementById("hide").onclick = function() {
    var o = document.getElementsByClassName("details");
    for ( var i = 0; i < o.length; i++ ) {
        if (o[i].style.display == 'none') {
            o[i].style.display = 'block';
        } else {
            o[i].style.display = 'none';
        }
    }
}

按预期工作,因此它隐藏和显示带有 class 的元素,但我无法为按钮添加内部文本更改。这是我的 html:

<button id="hide">Hide</button>
<ul>
    <li>
        <h3>First Item</h3>
        <ul class="details">
            <li>Detail 1</li>
            <li>Detail 2</li>
            <li>Detail 3</li>
        </ul>
    </li>
    <li>
        <h3>Second Item</h3>
        <ul class="details">
            <li>Detail 1</li>
            <li>Detail 2</li>
            <li>Detail 3</li>
        </ul>
    </li>
    <li>
        <h3>Third Item</h3>
        <ul class="details">
            <li>Detail 1</li>
            <li>Detail 2</li>
            <li>Detail 3</li>
        </ul>
    </li>
</ul>

应该这样做;

document.getElementById("hide").onclick = function() {
var o = document.getElementsByClassName("details");
for ( var i = 0; i < o.length; i++ ) {
    if (o[i].style.display == 'none') {
        o[i].style.display = 'block';
        this.innerText='hide';
    } else {
        o[i].style.display = 'none';
        this.innerText='show';
    }
}

}

更新了您的代码,运行 下面的脚本。

我拿了你的按钮并定位了 innerHTML。更多信息 here.

document.getElementById("hide").onclick = function() {
    var o = document.getElementsByClassName("details");
    var btn = document.getElementById("hide");
    for ( var i = 0; i < o.length; i++ ) {
        if (o[i].style.display == 'none') {
            o[i].style.display = 'block';
            btn.innerHTML = "Hide";
        } else {
            o[i].style.display = 'none';
            btn.innerHTML = "Show";
        }
    }
}
<button id="hide">Hide</button>
<ul>
    <li>
        <h3>First Item</h3>
        <ul class="details">
            <li>Detail 1</li>
            <li>Detail 2</li>
            <li>Detail 3</li>
        </ul>
    </li>
    <li>
        <h3>Second Item</h3>
        <ul class="details">
            <li>Detail 1</li>
            <li>Detail 2</li>
            <li>Detail 3</li>
        </ul>
    </li>
    <li>
        <h3>Third Item</h3>
        <ul class="details">
            <li>Detail 1</li>
            <li>Detail 2</li>
            <li>Detail 3</li>
        </ul>
    </li>
</ul>