[英]What's wrong with this JavaScript code?
var input = document.getElementById("myInput");
a.onkeydown = function() {
if (a.value.match("hi")) {
a.value.replace("hi", "span style='color:red;'>hi</span>");
}
};
<input type="text" id="myInput" />
It does not take any action to replace 'hi' with a red 'hi'. 无需采取任何措施将红色的“ hi”替换为“ hi”。
除非您省略某些内容,否则变量a
不会代表您的文本框。
You're missing the opening < before the span, for one. 您缺少跨度之前的开头<,只有一个。 Also, I don't know if you can nest HTML inside an input element. 另外,我不知道您是否可以在输入元素中嵌套HTML。 A better way would be to turn on a class/style that makes the text red if the value == 'hi'. 更好的方法是打开一个类/样式,如果值=='hi',则使文本变为红色。
a
which is not declared anywhere, I assume you mean input
您正在使用未在任何地方声明的变量a
,我假设您的意思是input
onkeyup
which will trigger the event as soon as you type hi
更好的选择是使用onkeyup
,一旦您键入hi
,它将触发事件 <script/>
is after the element so the element is ready in the dom. 确保<script/>
在元素之后,以便元素在dom中准备就绪。
Putting that all together you get this: 综上所述,您将获得:
<input type="text" id="myInput" />
<script type="text/javascript">
var input = document.getElementById("myInput");
input.onkeyup = function() {
if (input.value.match("hi")) {
input.value = input.value.replace("hi", "<span style='color:red;'>hi</span>");
}
};
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.