[英]How to fix Uncaught TypeError in JavaScript?
I'm trying to submit a form of a specific element in my webpage but i get a 我正在尝试在我的网页中提交一个特定元素的表单,但我得到了一个
Uncaught TypeError: Cannot read property 'form' of undefined
This is the JavaScript script for my webpage 这是我的网页的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>
Every one of the click handlers is referencing the exact same i
variable. 每个点击处理程序都引用完全相同的
i
变量。 By the time the button is clicked, i
has long ago been incremented to aTags.length
. 单击按钮时,
i
很久以前已经增加到aTags.length
。 So aTags[i]
resolves to aTags[aTags.length]
, which is undefined. 所以
aTags[i]
解析为aTags[aTags.length]
,这是未定义的。
Simplest solution is to just use let
instead of var
. 最简单的解决方案是使用
let
而不是var
。 That way, every time through the loop gets a new binding of the variable, and thus the click handlers are all associated with the correct value. 这样,每次循环都会获得变量的新绑定,因此单击处理程序都与正确的值相关联。
for (let i = 0; i < aTags.length; i++){
// rest of the code the same
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.