显示/隐藏onClick按钮不起作用

时间:2015-04-29 01:33:40

标签: javascript html css show-hide

嘿伙计们,我已经搜索了很多答案,但似乎没有任何答案,所以我将把我的代码放在这里,希望你能帮助我解决这个问题。

我将有两个按钮。第一个按钮(show_Chappie)将显示隐藏的内容和另一个按钮(hide_Chappie),并在单击时隐藏它。

第二个按钮(hide_chappie)将隐藏内容并返回第一个按钮(show_chappie)。 hide_chappie按钮本身也将被隐藏。

信息div从一开始就已隐藏。我使用display:none;

在CSS上完成了这个

到目前为止,这是我的HTML代码:

SHOW FULL COLUMNS FROM `table_im_trying_to_insert`

到目前为止,这是我的JavaScript代码:

<button class ="show_chappie" onclick="showInfo()">Show More</button>
<div class="info">Info here.</div>
<button class ="hide_chappie" onclick="hideInfo()">Show Less</button>

我还没有编写hide_chappie按钮的代码,因为我想先看看它是否正常工作。

那我在哪里错了?感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

您试图在id class之前获取元素,您应该将元素class更改为id,如下所示:

<button id="show_chappie" onclick="showInfo()">Show More</button>
<div id="info">Info here.</div>
<button id="hide_chappie" onclick="hideInfo()">Show Less</button>

答案 1 :(得分:1)

您应该将代码更改为:

<button id ="show_chappie" onclick="showInfo()" >Show More</button>
<div class="info">Info here.</div>
<button id= "hide_chappie" onclick="showInfo()">Show Less</button>

如果您想在此处使用课程,则应将您的Javascript代码更改为

function showInfo(){

                document.getElementByClass('chappie_info')[0].style.display = "inline-block";
                document.getElementByClass('show_chappie')[0].style.display = "none";
                document.getElementByClass('hide_chappie')[0].style.display = "inline-block";

            }

因为函数getElementsByClass返回一个集合,所以你应该添加[]来找出你想要的结果!

答案 2 :(得分:1)

将所有ID转换为类很烦人,您可以使用:

function showInfo(){

    document.getElementsByClassName('chappie_info').style.display = "inline-block";
    document.getElementsByClassName('show_chappie').style.display = "none";
    document.getElementsByClassName('hide_chappie').style.display = "inline-block";

}

现在几乎所有的浏览器都支持这一点,所以我不担心这一点。如果这仍然是一个问题,您需要支持古老的浏览器,请使用:

document.getElementsByClassName = function (a) {
    var b = document.getElementsByTagName('*'), i, c=[];
    for (i = 0; i < b.length; i += 1) {  b[i].getAttribute('class')===a&&c.push(b[i]);  }
    return c;
};
相关问题