我正在尝试将输入框与 id="b" 链接(位于内部div id="but1" .) 使用 JS 函数,给出所需的输出(仅在数组内计数)..但是我的初级逻辑在代码中没有发现任何问题,我犯了什么错误?
这是我第二次重写所有的 JS 函数,但我似乎仍然找不到问题所在。
function alert1() {
let arr = [];
arr.value = document.getElementById('a');
let b = document.getElementById('b');
b.value;
for (let i = 0; i < arr.length; i++) {
if (arr[i].length <= 10) {
console.log(arr[i].length + " ", "Mbaroi rasti 1");
b.value = "Mbaroi rasti 1";
return b;
} else if (arr[i].length >= 11 && arr[i].length <= 12) {
console.log(arr[i].length + " ", "Mbaroi rasti 2");
b.value = "Mbaroi rasti 2";
return b;
} else if (arr[i].length >= 13) {
console.log(arr[i].length + " ", "Mbaroi rasti 3");
b.value = "Mbaroi rasti 3";
return b;
}
}
}
alert1();
<body>
<div id="div1" style="text-align:center;">
<div id="but1">
<button id="button_1" onclick="document.getElementById('b').innerHTML=alert1()">Calc_bashkesia-1</button>
<label><b>InputBox</b></label>
<input type="text" id="a" placeholder="Enter Some Input" />
<input type="text" id="b" placeholder="Calculation output here" for="a" />
</div>
</div>
</body>
我希望 id="button_1"的按钮在 id="b"的输入框中输出alert1()回调的计算结果,但这并没有发生。
最佳答案
更改 HTML 中的 onclick 以调用您的函数。
也不需要数组或 for 循环。
我留在里面的返回
没有做任何事情。
function alert1 () {
const aValue = document.getElementById('a').value;
const b = document.getElementById('b');
if(aValue <= 10) {
console.log(aValue +" ", "Mbaroi rasti 1");
b.value = "Mbaroi rasti 1";
return b;
} else if(aValue >= 11 && aValue <= 12) {
console.log(aValue +" ", "Mbaroi rasti 2");
b.value = "Mbaroi rasti 2";
return b;
} else if(aValue >= 13) {
console.log(aValue +" ", "Mbaroi rasti 3");
b.value = "Mbaroi rasti 3";
return b;
}
}
<div id="div1" style="text-align:center;">
<div id="but1">
<button id="button_1" onclick="alert1()">Calc_bashkesia-1</button>
<label><b>InputBox</b></label>
<input type="text" id="a" placeholder="Enter Some Input"/>
<input type="text" id="b" placeholder="Calculation output here" for="a"/>
</div>
</div>
关于javascript - 如何将 Html 框与 Javascript 函数链接起来以给出预期的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57465420/