【问题标题】:I added the button of javascript but not working我添加了javascript的按钮但不起作用
【发布时间】:2019-10-10 06:22:53
【问题描述】:

<p id="para1">Hi</p>
<button onclick="style()">Submit</button>

<script>
function style(){
  var text= document.getElementById("para1").style.color="green";
}
</script>

我使用 javascript 添加了 html 代码。除按钮外,所有标题和 div 都可以正常工作。该按钮未添加或由于某些原因可能无法正常工作。请检查我的代码给出一些建议。当我使用与 html 相同的代码时,它运行良好。

【问题讨论】:

  • 请贴出你使用js添加html的代码
  • 请发布您的解决方案作为答案
  • Delete "var text=" 只写这段代码 document.getElementById("para1").style.color="green";

标签: javascript javascript-objects


【解决方案1】:

style 在 JavaScript 中具有特殊含义,请使用其他名称作为函数名称:

<p id="para1">Hi</p>
<button onclick="elementStyle()">Submit</button>

<script>
  function elementStyle(){
    document.getElementById("para1").style.color="green";
  }
</script>

【讨论】:

    【解决方案2】:

    另一种方法是向元素添加一个类,该类应该设置样式。然后你就可以很灵活地设计它了:

    <p id="para1">Hi</p>
    <button onclick="stylePara1()">Submit</button>
    
    <style>
      .green-text {
        color: green
      }
    </style>
    
    <script>
      function stylePara1(){
        document.querySelector('#para1').classList.add('green-text');
      }
    </script>

    或者使用内联语法:

    <p id="para1">Hi</p>
    <button onclick="document.querySelector('#para1').classList.add('green-text')">Submit</button>
    
    <style>
      .green-text {
        color: green
      }
    </style>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-07-15
      • 2020-10-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多