【问题标题】:I want to change background colour when I click input单击输入时我想更改背景颜色
【发布时间】:2021-11-05 14:40:05
【问题描述】:
 <input type="submit" value="Login" onclick="myFunction">

  <!-- Project -->
  <script>
    
    function myFunction(){
      document.getElementById("input[tpye="submit"]").style.backgroundColor="blue";
    }
    
  </script>

【问题讨论】:

  • 请将您尝试过的代码添加为minimal reproducible example,包括您尝试更新的 HTML。您还有一个错字:“tpye”。你试图在双引号内使用双引号,这会给你一个错误。您应该查看您的 devtools (F12) 控制台以尝试调试您的代码。您可能也应该阅读getElementById 的文档。看起来你想要querySelector
  • 对不起@isherwood。我没有意识到你保留了 Sam 的编辑。我误以为你把它拿出来了。我已经回到最初的问题(但有格式),这样我们就不会编造东西,只是根据我们认为应该存在的东西来猜测答案。
  • 没有人添加东西。 OP在那里有一个输入。请参阅原帖的source
  • 我认输。但是,如果我必须查看问题的来源而不是查看问题,那并不是很好的用户体验。显然,国际海事组织。

标签: javascript html function input onclick


【解决方案1】:

getElementById 获取具有该 id 的元素。您可能正在寻找querySelector,它将选择与该选择器匹配的元素:

function myFunction(){ 
    document.querySelector("input[type='submit']").style.backgroundColor="blue";
 }

【讨论】:

  • 我知道您(Spectric)知道这一点,但对于 OP:您不应该在现代 Web 开发中使用 .style。您应该使用 .classList 来通过类应用样式更改,而不是出于各种原因(例如特定权重问题)添加内联样式。
【解决方案2】:

你的代码sn-p犯了三个错误

  1. 你没有给函数调用()
  2. 您在“类型”字的 querySelector 中写错了拼写
  3. 您正在调用 getElementById() 函数,但您没有为输入框提供 id

<input type="submit" value="Login" onclick="myFunction()">

<!-- Project -->
<script>
  
  function myFunction(){
    document.querySelector("input[type='submit']").style.backgroundColor="blue";
  }
  
</script>

【讨论】:

    【解决方案3】:

    在 javascript 函数中,您使用的是“getElementById”,这意味着它将查找具有您提供的 id 的 DOM 元素,问题是您没有提供任何 id。

    你必须先给按钮一个id

    <button id="some_id">Click</button>
    

    然后以这种方式对齐你的函数。

    function myFunction(){ document.getElementById("some_id").style.backgroundColor="blue"; }
    

    【讨论】:

      【解决方案4】:

      这是我对您问题的解决方案。在您的情况下,您有某种类型的输入,您首先需要向输入添加一个事件侦听器,它将在特定事件上执行某些功能。在我们的例子中,我们将执行更改颜色功能。

      这是您问题的快速解决方案。

      let button = document.getElementById('changecolor');
      
      let input = document.getElementById('basic-input');
      
      
      function changeBackground(){
          // Change the background of the page
          document.body.style.background = 'red';
        
        // Change background of the button
        button.style.background = 'blue';
      }
      
      button.addEventListener('click' , changeBackground);
      
      input.addEventListener('click' , changeBackground);
      <button id="changecolor">Change background</button>
      
      <input type="text" placeholder="basic input" id="basic-input">

      【讨论】:

        猜你喜欢
        • 2019-09-01
        • 2014-06-12
        • 1970-01-01
        • 2014-10-09
        • 2011-06-05
        • 2013-09-27
        • 2017-08-02
        • 2019-05-22
        相关资源
        最近更新 更多