javascript - 如何将 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>
解决方案
您可以尝试以下方法:
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>
推荐阅读
- jsf - 警告:此页面调用 XML 命名空间 http://primefaces.org/ui/extensions 声明,前缀为 pe,但该命名空间不存在标记库
- macos - 有什么方法可以在 AppleScript 中暂时暂停脚本?
- git - Unity .gitignore 不忽略 .asset 文件
- python - 这种递归二分搜索是如何工作的?用于查找 bst 中的第 k 个最小节点
- javascript - 带有 4 位小数的货币格式正则表达式,如果没有则不显示美分
- c++ - C++ Setter 不给派生类赋值
- javascript - 用另一个数组创建对象数组
- javascript - 异步需要回调函数吗
- r - 缺少某些日期时,Dplyr 在日期之间更改列指示符
- git - 目录名称无效 - Git 和 R Studio 版本控制