我对JavaScript完全陌生,并且不知道为什么这不起作用。当我单击输入框并输入少于5个字符时,我想要显示一条消息。消息根本没有显示。源代码:https://jsfiddle.net/015por64/
<html>
<body>
<form id="form>">
<input id="input">
<div id="text"> Test </div>
</input>
</form>
</body>
</html>
<script>
function checkUserName(e, minLength) {
var username = document.getElementById("input");
var usernameLength = username.textContent;
if (usernameLength.value.length < 5) {
msg = "Your username must consist of at least five characters."
};
else {
msg = "";
text.innerHTML=msg
};
}
var text = document.getElementById("text");
text.addEventListener("blur", function(e) {checkUserName(e, 5)}, false)
</script>
&#13;
答案 0 :(得分:1)
您的代码几乎没有问题:
#input
,而不是div#text
。#input
而不是textcontent
;
,否则会出现语法错误。
<html>
<body>
<form id="form>">
<input id="input">
<div id="text"> Test </div>
</input>
</form>
</body>
</html>
<script>
function checkUserName(e, minLength) {
var username = document.getElementById("input");
var usernameLength = username.value;
if (usernameLength.length < 5) {
msg = "Your username must consist of at least five characters.";
text.innerHTML=msg;
}else {
msg = "";
text.innerHTML=msg;
};
}
var text = document.getElementById("text");
document.getElementById('input').addEventListener("blur", function(e) {checkUserName(e, 5);}, false)
</script>
答案 1 :(得分:0)
它应该是您必须放置 blur 事件侦听器的输入。
var input = document.getElementById("input");
由于你在函数之外没有使用text
,所以最好在里面定义它。