首页 > 解决方案 > 如何将 id 连接到 html 和 javascript 中的触发函数

问题描述

使用下面的代码,我试图让它响应静音和静音的输入。因此,当在文本框中输入静音或静音时,它会将静音的颜色更改为红色,静音的颜色变为绿色,在这种情况下,链接的 id 为 id="text" 和 "text1"。谢谢!

HTML:

  <!DOCTYPE html>
    <html>
    <body>

    <p>Write something in the text field to trigger a function.</p>

    <input type="text" id="myInput" oninput="myFunction()">

    <p id="demo"></p>

    <script>
    function myFunction() {
      var x = document.getElementById("myInput").value;
      document.getElementById("demo").innerHTML = "You wrote: " + x;
    }
    </script>

    </body>
    </html>

想要链接的 HTML:

<h1 class="l1-txt1 txt-center p-t-0 p-b-10">
    <p id="text1" style="color:white; font-weight: 600"></p>
</h1>

<h1 class="l1-txt1 txt-center p-t-0 p-b-60">
    <p id="text" style="color:crimson; font-weight: 600"></p>
</h1>

标签: javascripthtmlcsstelnet

解决方案


您可以尝试以下方法:

function myFunction() {
  var x = document.getElementById("myInput").value;
  var t1 = document.getElementById("text1");
  var t2 = document.getElementById("text");
  document.getElementById("demo").innerHTML = "You wrote: " + x;
  if(x.trim().toLowerCase() == 'mute'){
    t1.style.color = 'green';
    t2.style.color = 'green';
  }
  else if(x.trim().toLowerCase() == 'muteon'){
    t1.style.color = 'red';
    t2.style.color = 'red';
  }
}
<p>Write something in the text field to trigger a function.</p>

<input type="text" id="myInput" oninput="myFunction()">

<p id="demo"></p>
<h1 class="l1-txt1 txt-center p-t-0 p-b-10">
  <p id="text1" style="color:white; font-weight: 600">Text 1</p>
</h1>

<h1 class="l1-txt1 txt-center p-t-0 p-b-60">
  <p id="text" style="color:crimson; font-weight: 600">Text</p>
</h1>


推荐阅读