【问题标题】:I want to change the onclick of a button using javascript, but it's not working我想使用 javascript 更改按钮的 onclick,但它不起作用
【发布时间】:2010-11-02 14:38:38
【问题描述】:

好的,所以我正在尝试编写一个简单的显示/隐藏内容按钮,但我想使用两个不同的功能显示和隐藏内容。现在它隐藏得很好,但它不会重新显示。

<html>
 <head>
 <title>Test</title>

 <script type="text/javascript">
  function hidecontent(){
   document.getElementById("content").style.display = "none";
   document.getElementById("hidebutton").value = "+";
   document.getElementById("hidebutton").onclick = showcontent();
  }

  function showcontent(){
   document.getElementById("content").style.display = "block";
   document.getElementById("hidebutton").value = "-";
   document.getElementById("hidebutton").onclick = hidecontent();
  }
 </script>

 <style type="text/css">
  #content{
   border: 1px solid #003333;
   background-color: #000033;
   color: #ffffff;
   height: 500px;
   width: 500px;
   text-align: center;
   display: block;
  }

  #hidebutton{
   border: 1px solid #003333;
   background-color: #000033;
   color: #ffffff;
   padding: 0px 0px 0px 0px;
   margin: 0px 0px 0px 0px;
  }
 </style>

 </head>

 <body>
  <form>
   <input id="hidebutton" type="button" value="-" onclick="hidecontent()" />
  </form>

  <?php
   echo '<div id="content">Hello world!</div>';
  ?>
 </body>
</html>

【问题讨论】:

  • hidecontent() 应该没有结束大括号,例如document.getElementById("hidebutton").onclick = hidecontent;。这就是问题所在:)

标签: php javascript html css


【解决方案1】:

这样做

document.getElementById("hidebutton").onclick = hidecontent;

【讨论】:

  • 实际上,萨法兹,确实如此。 O__O
  • 技术上不应该是这样的:document.getElementById("hidebutton").onclick
【解决方案2】:

不需要两个函数,你也可以这样做:

function show_hide(){
    var ds = document.getElementById("content");
    var btn = document.getElementById("hidebutton");

    if (ds.style.display === 'block'){
       ds.style.display = 'none';
       btn.value = '+';
    }
    else {
       ds.style.display = 'block';
       btn.value = '-';
    }
}

以后你可以这样调用函数:

var btn = document.getElementById("hidebutton");
btn.onclick = show_hide;

【讨论】:

  • 该死的,你打败了我。不管怎样,William,这种编码风格比在你的按钮上有一个 onclick 属性要好得多。将行为与您的标记分开。
【解决方案3】:

document.getElementById("hidebutton").onclick = showcontent; //删除()

document.getElementById("hidebutton").onclick = hidecontent; //删除()

【讨论】:

    猜你喜欢
    • 2021-09-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-18
    • 2018-07-11
    • 2020-11-12
    • 1970-01-01
    • 2018-05-10
    相关资源
    最近更新 更多