如何在JavaScript中修复Uncaught TypeError?

问题描述 投票:1回答:1

我正在尝试在我的网页中提交一个特定元素的表单,但我得到了一个

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>
javascript html dom
1个回答
3
投票

每个点击处理程序都引用完全相同的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
}
© www.soinside.com 2019 - 2024. All rights reserved.