ReferenceError:未定义addEvent

时间:2015-01-07 16:44:54

标签: javascript css

我是Javascript的新学习者,我无法检测到javascript错误。主要问题是什么。在这种情况下请帮助。我在检查元素时遇到错误。 ReferenceError:未定义addEvent

http://jsfiddle.net/v7p1bc5u/

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <script src="jsscript.js"></script>
</head>
<body>
    <h1>Window Open and Close</h1>
    <form action="">
        <p>
            <input type="button" id="create-window" value="Create New Window">
            <input type="button" id="close-window" value="Close New Window">
        </p>
    </form>
</body>
</html>



addEvent(window,'load',initialize);

    function initialize(){
        if(document.getElementById)
        {
            var oButtonCreate = document.getElementById("create-window");
            var oButtonClose = document.getElementById("close-window");
            if (oButtonCreate && oButtonClose)
            {
                oButtonCreate.onclick = makeNewWindow;
                obuttonClose.onclick =closeNewWindow;
            }
        }
    }

    var newWindow;

    function makeNewWindow()
    {
        newWindow = window.open("","","height=300, width=300")  
    }
    function closeNewWindow()
    {
        if(newWindow)
        {
            newWindow.close();
            newWindow =null;
        }
    }

2 个答案:

答案 0 :(得分:0)

读同一本书,也有同样的问题。 问题在于它们是预定义函数,并在本书的早期描述。 但是其他用户建议直接使用addEventListener,这似乎是更好的做法

function addEvent(to, type, fn){
    if(document.addEventListener){
        to.addEventListener(type, fn, false);
    } else if(document.attachEvent){
        to.attachEvent('on'+type, fn);
    } else {
        to['on'+type] = fn;
    }  
}

答案 1 :(得分:0)

我利用了下面的那个结构,它起作用了。感谢@IvanN给了这个想法addEventListener

function initialize(){
    if(document.getElementById){
        var oButtonRewrite = document.getElementById('rewritePage');
        
        //if it exists...
        if(oButtonRewrite){
            oButtonRewrite.addEventListener('click',reWrite);
        }
    }
}
window.addEventListener('load',initialize);