繁体   English   中英

Vanilla JS - 通过单击按钮隐藏和显示 div 的功能

[英]Vanilla JS - function to hide and show a div by clicking a button

我有问题; 当我单击一个从下拉列表中获取值的按钮时,它应该显示分配给他的匹配值的 div。

到目前为止,我的代码按预期执行,它显示了相应的 div,但随后它恢复并在 3 秒后将其隐藏。 这可能是一个简单的错误,感谢您的帮助。

在头:

    var e = document.getElementById("graph_req_ID");
    var indexValue = e.options[e.selectedIndex].value;
    var strValue = e.options[e.selectedIndex].text;

    function getGraphReq(){       
    if (strValue == "Default") {
        graph3.style.display = "block";

    } else {
        graph3.style.display = "none";
    }             
    }

我的按钮:

    <button onclick="getGraphReq()"></button>

隐藏的div:

    <div id="graph3">
         <h4>this content should show after clicking the button</h4>
    </div>

不确定您的代码有什么问题,但这是预期的行为吗?

 var e = document.getElementById("graph_req_ID"); var indexValue = e.options[e.selectedIndex].value; function getGraphReq() { var strValue = e.options[e.selectedIndex].text; if (strValue == "Default") { graph3.style.display = "block"; } else { graph3.style.display = "none"; } } getGraphReq();
 <select id='graph_req_ID'> <option value='Default'>Default</option> <option value='Other' selected>Other</option> </select> <button onclick="getGraphReq()">getGraphReq</button> <div id="graph3"> <h4>this content should show after clicking the button</h4> </div>

 function getGraphReq(){ var e = document.getElementById("graph_req_ID"); var indexValue = e.options[e.selectedIndex].value; var strValue = e.options[e.selectedIndex].text; if (strValue == "Default") { graph3.style.display = "block"; } else { graph3.style.display = "none"; } }
 <select id="graph_req_ID"> <option value="Default">Default</option> <option value="Default">foo</option> </select> <button onclick="getGraphReq()">Click me</button> <div id="graph3"> <h4>this content should show after clicking the button</h4> </div>

我将这些变量移到了函数中。 然后,当您执行该函数时,它将为变量分配正确的值。 这是您需要的预期输出吗?

如果该元素不应该在加载时可见,并且只能通过单击事件显示,则:

<div id="graph3" style="display:none">

你的代码对我有用。 可能是文件中的其他内容导致了您的问题。 很难说你发布了什么。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM