gpt4 book ai didi

javascript - 事件 : What are good practices for avoiding inline Javascript? 的范围问题

转载 作者:行者123 更新时间:2023-12-02 19:06:24 25 4
gpt4 key购买 nike


我似乎在直接匿名函数内使用 addEventListener 时遇到范围问题。

在事件监听器内部,我创建了一个 Javascript“类”的实例,该实例是在立即函数之外构造的(使用构造函数和原型(prototype))。

为了保持良好的实践,我想使用立即函数来避免全局变量,并使用 addEventListener 来避免使用内联 Javascript(从而将其与 html 分开)。

那么,我怎样才能在不出现范围问题的情况下正确地做到这一点,以及这样做的良好做法是什么?

<小时/>这是我的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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com