JavaScript OO 编程语法帮助菜鸟

javascript oo programming syntax help for a noob

本文关键字:帮助 菜鸟 语法 编程 OO JavaScript      更新时间:2023-09-26

我第一次尝试编写一些 oo 风格的 js。 当我的页面加载时,它正在执行我的 login() 函数两次,而我想触发 login() 的事件侦听器根本不起作用。 任何帮助将不胜感激。 这是我的代码:

(function( window, undefined ) {
var document = window.document,
    navigator = window.navigator,
    location = window.location;
//build the login button
var DA = {
    width : '70px',
    height : '20px',
    createLoginButton : function(){
        var a = document.createElement('a');
        a.style.width = this.width;
        a.style.height = this.height;
        a.style.cursor = 'pointer';
        var div = document.createElement('div');
        div.id = 'da_login_button';
        div.onclick = DA.login();
        div.innerHTML = "client login";
        div.style.width = this.width;
        div.style.height = this.height;
        div.style.backgroundColor = '#59724A';
        div.style.color = 'white';
        div.style.border = '4px solid #6B5D49';
        div.style.padding = '3px';
        div.style.textAlign = 'center';
        a.appendChild(div);
        return a;
    },
    //write the button to the dom
    writeLoginButton : function(){
        var dest = document.getElementById('digital_arborist_login');
        dest.style.width = this.width;
        dest.style.height = this.height;
        var theButton = DA.createLoginButton();
        dest.appendChild( theButton );
        theButton.addEventListener("click", DA.login(), false);
    },
    //detect ssl
    isSecure : function(){
        if (location.protocol === 'https:') {
            return true;
        } else {
            return false;
        }
    },
    // the login function
    login : function(){ 
        alert('href: '+location.href+'<br />protocol: '+location.protocol);
    },
};  
window.DA = DA; 
})( window )
// start the magic
DA.writeLoginButton();

这是我测试代码的网页。

theButton.addEventListener("click", DA.login(), false);

在此行中,将DA.login()更改为仅DA.login。 当你执行DA.login()时,你正在将login()函数的结果undefined)传递给点击处理程序,而不是函数本身。

它应该是:

theButton.addEventListener("click", DA.login, false);

编辑:div.onclick = DA.login();也应该div.onclick = DA.login;

更改以下内容:

theButton.addEventListener("click", DA.login(), false);

自:

theButton.addEventListener("click", DA.login, false);

而这个:

div.onclick = DA.login();

自:

div.onclick = DA.login;

您希望在每种情况下将函数本身分配为回调。 您实际上是在执行函数并将函数调用的结果分配为回调... 这就是为什么您的"登录"方法在启动时运行两次以及您的点击事件无法正常运行的原因。

还应从第一行中删除undefined参数。 undefined是javascript中的一个关键字,老实说,我很惊讶你没有从中得到语法错误。 它应如下所示:

(function(window) {