简单的Javascript错误让我疯了

时间:2015-06-02 01:11:07

标签: javascript

这让我疯了。我在下面放了html和javaScript代码。每当我刷新页面时,我都会得到Uncaught TypeError:screen.addEventListener不是一个函数。我为屏幕插入任何其他变量或ID,它工作正常。

HTML代码

<!DOCTYPE html>
<head>
    <meta charset="utf-8">
    <title>Calculator</title>
    <link rel="stylesheet" href="css/reset/reset.css">
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <div id="calculator">
        <div id="screen">
        </div>
        <div id="layout">
            <ul id="first-row" class="btn-row">
                <li><button>C</button></li>
                <li><button>=</button></li>
            </ul>
            <ul id="sec-row" class="btn-row">
                <li><button>7</button></li>
                <li><button>8</button></li>
                <li><button>9</button></li>
                <li><button>+</button></li>
            </ul>
            <ul id="third-row" class="btn-row">
                <li><button>4</button></li>
                <li><button>5</button></li>
                <li><button>6</button></li>
                <li><button>-</button></li>
            </ul>
            <ul id="fourth-row" class="btn-row">
                <li><button>1</button></li>
                <li><button>2</button></li>
                <li><button>3</button></li>
                <li><button>*</button></li>
            </ul>
            <ul id="fifth-row" class="btn-row">
                <li><button>0</button></li>
                <li><button>/</button></li>
            </ul>
        </div>
    </div>
    <script src="js/app.js">
    </script>
</body>
</html>

JavaScript代码

var screen = document.getElementById('screen');
var btn = document.getElementsByTagName('button');
var clear = btn[0];
var equals = btn[1];
var seven = btn[2];

clear.addEventListener('click', here);
screen.addEventListener('click', function(){
    alert('wth');
});

1 个答案:

答案 0 :(得分:2)

You have a naming issue. It is clashing with the window.screen object

console.log(window.screen);

MDN window.screen

将变量重命名为其他内容并且工作正常。

&#13;
&#13;
var screenX = document.getElementById("screen");
screenX.addEventListener("click", function() { alert("x"); });
&#13;
<div id="screen">Click</div>
&#13;
&#13;
&#13;

或将其从全球范围中删除

&#13;
&#13;
(function () {
    var screen = document.getElementById("screen");
    screen.addEventListener("click", function() { alert("x"); });
}());
&#13;
<div id="screen">Click</div>
&#13;
&#13;
&#13;