[英]Uncaught typeError : input.addEventListener is not a function
首先,我選擇了聯系表單容器內的所有輸入標簽,然后添加了click事件偵聽器並調用了一個函數。 那不行
它引發錯誤:Uncaught TypeError:input.addEventListener不是一個函數。
<div class="form-container">
<h1>SEND US A MESSAGE</h1>
<div class="form">
<input type="text" placeholder="Full Name">
<input type="text" placeholder="E-Mail">
<textarea name="Message" id="message" cols="30" rows="10" placeholder="Message"></textarea>
<button><i class="fa fa-paper-plane" aria-hidden="true"></i>SEND</button>
</div>
</div>
.form-container {
margin: 5rem 0;
height: auto;
// text-align: center;
h1 {
color: $header-main;
font-size: 2rem;
text-align: center;
}
.form {
input[type="text"],
textarea,button {
display: block;
margin: 2rem auto;
width: 600px;
padding: 1rem;
border-radius: 1rem;
border: 2px solid #d6cfcf;
outline: none;
}
}
}
<script>
// contact form
const input = document.querySelectorAll('.form-container input');
input.addEventListener('click', function () {
console.log('che che che');
});
</script>
const listOfInput = document.querySelectorAll('.form-container input')
for (let input of listOfInput) {
input.addEventListener('click', function () {
console.log('che che che');
});
}
您正在嘗試在HTMLCollection上調用addEventListener-function。
嘗試這個:
const input = document.querySelectorAll('.form-container input');
for(let i = 0; i < input.length; i++){
input[i].addEventListener('click', function () {
console.log('che che che');
});
}
根據https://developer.mozilla.org/zh-CN/docs/Web/API/Document/querySelectorAll
document.querySelectorAll返回一個nodeList,它是一個數組。 因此,您不能以這種方式將eventListener分配給所有它們。 你必須
input.forEach( inp => inp.addEventListener(...))
使用for循環迭代每個輸入元素
const input = document.querySelectorAll('.form-container input');
for (var i = 0 ; i < input.length; i++) {
input[i].addEventListener('click', function () {
console.log('che che che');
});
}
Element.querySelectorAll()返回類似於數組的NodeList
,可以通過forEach()
進行迭代。
const input = document.querySelectorAll(`.form-container input`);
input.forEach( function(element){
element.addEventListener(`click`,function(){
console.log(`clicked`);
});
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.