![](/img/trans.png)
[英]How to get the current value of a form input updated at each change without using jquery only using javaScript
[英]Get and set current input value without Jquery
不使用jQuery就可以獲取當前輸入值嗎? 我的意思是,我不想使用document.getElementById / class。 我想通過輸入標簽獲取元素。
我已經用jQuery實現了這一點:
$(document).on('keyup', 'input', function(e) {
console.log($(this).val());
})
並且適用於所有輸入。
<div>
<input type="text" value="">
<input type="text" value="">
</div>
我不知道如何將jQuery代碼轉換為純JavaScript代碼。 我嘗試這樣:
document.querySelector('input').addEventListener('input', function (evt) {
console.log(this.value);
});
但是,僅對第一個輸入有效。 有任何想法嗎?
您需要使用函數querySelectorAll
來獲取整個元素集。 然后,您需要遍歷這些元素並綁定必要的事件。
函數querySelector
僅返回找到的第一個元素。
document.querySelectorAll('input').forEach(function(input) { input.addEventListener('input', function(evt) { console.log(this.value); }); })
<div> <input type="text" value=""> <input type="text" value=""> </div>
您可以使用document.getElementsByTagName
並遍歷它們
for (var i=0; i< document.getElementsByTagName("input").length; i++) { document.getElementsByTagName("input")[i].addEventListener('input', function(evt) { console.log(this.value); }); }
<div> <input type="text" value=""> <input type="text" value=""> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.