导致控制台中出现未定义错误的对象

Object causing an undefined error in console

本文关键字:未定义 错误 对象 控制台      更新时间:2023-09-26
已经

没有足够接近这个的东西了......至少我的新手头脑可以理解。

我只是想创建一个具有方法的全局包含对象,其中包含创建和使用 AJAX 请求的说明。 然后,我继续为按钮创建事件侦听器。然后,我得到以下控制台输出。

Port: Could not establish connection. Receiving end does not exist. -This was deleted-.net/:1
Uncaught ReferenceError: globOject is not defined script.js:21
Port: Could not establish connection. Receiving end does not exist. -This was deleted-.net/:1
Exception in onResRdy: TypeError: Cannot read property 'htmlRes' of undefined ContentScript.js:84

确定我在这里做错了很多。让我知道我需要包含哪些其他信息才能获得这方面的帮助。

var globObject = {
sendToServer: function () {
    alert('you got to me at least!');
    var xhr;
    if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
        xhr=new XMLHttpRequest();
    }
    else {// code for IE6, IE5
        xhr=new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhr.open('POST', 'counterDoc.php', true);
    xhr.send();
},
counterClick: function (counter) {
    alert('you got here!');
    counter += 1;
    this.sendToServer();
}};
var button = document.getElementById('submbut').addEventListener('click',globOject.counterClick(0), true);
  1. 修复我在评论中提到的错别字,也@Bonakid提到过。 globOject.counterClick(0), true);应该globObject.counterClick(0), true);

  2. 不要将globObject.counterClick(0)用于回调函数,而应使用globObject.counterClick。定义globObject后,将立即调用第一个。

  3. 不要使用this.sendToServer();,而是使用globObject.sendToServer();counterClick方法中的thisdocument.getElementById('submbut')这是一个 HTML 元素。将console.log(this)添加到counterClick,您将看到。

此处的工作演示

更改此设置

var button = document.getElementById('submbut').addEventListener('click',globOject.counterClick(0)

var button = document.getElementById('submbut').addEventListener('click',globObject.counterClick(0)

这部分有一个印刷错误

globOject.counterClick(0)