【问题标题】:HTML & Javascript, how can I make a button appear in a function? [closed]HTML & Javascript,如何让按钮出现在函数中? [关闭]
【发布时间】:2014-12-16 15:26:58
【问题描述】:

我还是 HTML 和 JS 的新手,但我想制作一个让按钮出现在网页上的功能......我尝试了一些这样的事情:

HTML:

<span id="buttonAppear"></span>

JS:

function buttonFunction(){
     document.getElementById("buttonAppear").innerHTML = "<button onclick="secondFunction()">Some text here</button>";
}

当然,这没有用。我很想听听一个很好的方法来实现这一点。 提前致谢!

【问题讨论】:

  • 为什么不起作用?你有没有得到一个错误,你试过调试它吗?它最有可能是由于报价。尝试在按钮 html 周围使用 ' 而不是 "
  • \" 可能有用。基本的东西。

标签: javascript html button


【解决方案1】:

它应该会出现。 你必须削减你的 innerHtml 或使用单引号,这样你就不会在混合它们时弄乱:

function buttonFunction(){
     document.getElementById("buttonAppear").innerHTML = '<button onclick="secondFunction()">Some text here</button>';
}

【讨论】:

  • 啊,是的,这行得通。简单的初学者错误......现在感觉很愚蠢,哈哈..感谢您的回答!几分钟后接受。
【解决方案2】:

问题在于您使用引号,正如 Andrea 在他的回复中指出的那样。您的版本只有在您转义内部双引号时才有效,如下所示:

function buttonFunction(){
     document.getElementById("buttonAppear").innerHTML = "<button onclick=\"secondFunction()\">Some text here</button>";
}

【讨论】:

    【解决方案3】:

    您需要先转义附加到 DOM 的内容。您可能还想在页面加载或发生其他事件时运行它。

    使用 jQuerys .ready() 将在页面完全加载时加载您拥有的任何内容。然后传入你的函数:

    $(document).ready(function(){
      document.getElementById("buttonAppear").innerHTML = '<button
        onclick=\'secondFunction()\'>Some text here</button>';
    });
    

    【讨论】:

      【解决方案4】:

      如果按钮总是相同的,您可以动态显示和隐藏它...

      /*In your CSS*/
       .hidden {
          display: none;
      }
      .show {
         display: inline;
      }
      <!-- In your HTML -->
      <button id="button" class="hidden">test</button>
      
      // In your js
      function toggleButton() {
          document.getElementById("button").className = 'show'; 
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-07-30
        • 1970-01-01
        • 2022-10-07
        • 1970-01-01
        • 2013-07-13
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多