我的目标是为用户名创建一个文本,用户可以在其中输入文本,但如果单词少于五个字母,那么下面的段落会提醒他们用户名少于五个字母,我正在使用事件处理程序来去做这个,我仍在学习解决方法,所以我想知道我做错了什么。我还为旧版浏览器添加了后备代码。
<form>
<input type="text" id="text1"
/><p id="response"></p>
</form>
function input(e, minlength) {
var target1 = e.target || e.srcElement; //element which the event is working on
var paragraph1 = target.nextSibling;
if (!e) {
e = window.event;
}
if (target1.value.length < minlength) {
paragraph1.textContent =
"Your username should be" + minlength + "letters and above";
}
}
var input1 = document.getElementById("text1");
if (input1.addEventListener) {
input1.addEventListener(
"blur",
function (e) {
input(e, 5);
},
false
);
}
else{
input1.attachEvent(
"onblur",
function (e) {
input(e, 5);
},
false
);
}
这段代码应该可以做到!
// Select the input and paragraph elements
const inputElement = document.getElementById('text1');
const paragraphElement = document.getElementById('response');
// Add an event listener to the input element
inputElement.addEventListener('input', function() {
// Get the value of the input
const inputValue = inputElement.value;
// Check the length of the input value
if (inputValue.length < 5) {
paragraphElement.textContent = 'Input is less than 5 characters';
} else {
paragraphElement.textContent = 'Input is 5 characters or more';
}
});
<form>
<input type="text" id="text1"
/><p id="response"></p>
</form>