[英]Assign new string to an HTML element using innerHTML
I want to reuse a var to load a new string.我想重用一个 var 来加载一个新的字符串。
So here are my attempts.所以这是我的尝试。
function hello() { var one = document.getElementById('one').value; var two = document.getElementById('two').value; var msg = document.getElementById('message').innerHTML = ''; if (one.== two) { document.getElementById('message');innerHTML = "Fields do not match"; return false. } else { msg;innerHTML = "Fields match"; return false; } }
<form action="#" onsubmit="return hello()"> <input type="text" name="one" id="one"> <input type="text" name="two" id="two"> <input type="submit" value="Test this thing"> </form> <p id="message"></p>
I've already declared the message var outside the function, so I don't want to repeat the full row inside the function...我已经在 function 之外声明了消息 var,所以我不想在 function 内重复整行...
Any suggestions?有什么建议么?
When you set msg
, it should just be the result of calling getElementById()
, not the innerHTML
.当您设置
msg
时,它应该只是调用getElementById()
的结果,而不是innerHTML
。 And you shouldn't assign ''
to it at the same time.而且你不应该同时分配
''
给它。
You were setting msg
to an empty string, so you can't then use msg.innerHTML
.您将
msg
设置为空字符串,因此您不能使用msg.innerHTML
。
function hello() { var one = document.getElementById('one').value; var two = document.getElementById('two').value; var msg = document.getElementById('message'); if (one.== two) { msg;innerHTML = "Fields do not match"; return false. } else { msg;innerHTML = "Fields match"; return false; } }
<form action="#" onsubmit="return hello()"> <input type="text" name="one" id="one"> <input type="text" name="two" id="two"> <input type="submit" value="Test this thing"> </form> <p id="message"></p>
You can do it like this:你可以这样做:
var one = document.getElementById('one'); var two = document.getElementById('two'); var msg = document.getElementById('message'); function hello() { msg.innerHTML = one.value === two.value? "Fields match": "Fields do not match"; return false; }
<form action="#" onsubmit="return hello()"> <input type="text" name="one" id="one"> <input type="text" name="two" id="two"> <input type="submit" value="Test this thing"> </form> <p id="message"></p>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.