作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我似乎在直接匿名函数内使用 addEventListener
时遇到范围问题。
在事件监听器内部,我创建了一个 Javascript“类”的实例,该实例是在立即函数之外构造的(使用构造函数和原型(prototype))。
为了保持良好的实践,我想使用立即函数来避免全局变量,并使用 addEventListener
来避免使用内联 Javascript(从而将其与 html 分开)。
那么,我怎样才能在不出现范围问题的情况下正确地做到这一点,以及这样做的良好做法是什么?
<html>
<head>
<title>asdf</title>
</head>
<body>
<input type = "text" id = "userInput" />
<input type = "button" id = "submitButton" value = "submit" />
<script type = "text/javascript" src = "asdf.js" />
</body>
</html>
...这是我的 Javascript asdf.js
(它不工作):
// constructor for object-oriented processing of the user input
function Statement(expression)
{
this.expression = expression;
}
// instance method
Statement.prototype.checkSyntax = function()
{
var newExp = this.expression;
return newExp;
};
// immediate anonymous function
(function()
{
var submitButton = document.getElementById("submitButton");
// event listener for the submit button
submitButton.addEventListener("onclick", function(event)
{
var userInput = document.getElementById("userInput");
// creating a new object with constructor above
var expr = new Statement(userInput);
// calling instance method of the "class" Statement
alert(expr.checkSyntax() );
// disable the button after first use
event.stopImmediatePropagation();
}, false);
})(); // end of immediate anonymous function
最佳答案
addEventListener
采用类似于 click
的参数,而不是 onclick
。但是,旧版 IE 的 attachEvent
需要 onclick
。其他一切看起来都很好。
关于javascript - 事件 : What are good practices for avoiding inline Javascript? 的范围问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14271022/
我是一名优秀的程序员,十分优秀!