[英]How to fix Uncaught TypeError in JavaScript?
我正在嘗試在我的網頁中提交一個特定元素的表單,但我得到了一個
Uncaught TypeError: Cannot read property 'form' of undefined
這是我的網頁的JavaScript腳本
<script type="text/javascript">
var aTags = document.getElementsByName("s");
for (var i=0;i<aTags.length;i++){
aTags[i].addEventListener('click', function(e){
e.preventDefault();
bootbox.confirm({
message: "This is a confirm with custom button text and color! Do you like it?",
closeButton: false,
buttons: {
confirm: {
label: 'Yes',
className: 'btn-success'
},
cancel: {
label: 'No',
className: 'btn-danger'
}
},
callback: function (result) {
if(result){
aTags[i].form.submit();
}
}
});
});
}
</script>
每個點擊處理程序都引用完全相同的i
變量。 單擊按鈕時, i
很久以前已經增加到aTags.length
。 所以aTags[i]
解析為aTags[aTags.length]
,這是未定義的。
最簡單的解決方案是使用let
而不是var
。 這樣,每次循環都會獲得變量的新綁定,因此單擊處理程序都與正確的值相關聯。
for (let i = 0; i < aTags.length; i++){
// rest of the code the same
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.