调用与事件关联的匿名函数 [英] Invoking anonymous function associated with an event

查看:26
本文介绍了调用与事件关联的匿名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下代码不起作用:

<input id="inp" type="text"
onfocus="(function(){document.getElementById('inp').style.background="yellow";})">

但是这段代码按我希望的那样工作:

But this code works as I wish it to work:

<input id="inp" type="text"
onfocus="(function(e){document.getElementById('inp').style.background ='yellow';}(this)">

为什么第一个代码不起作用?

Why doesn't the first code work?

推荐答案

第一个不起作用,因为它被括在括号中,因此它是一个函数表达式",而不是一个函数声明".表达式旨在评估",因此当您的元素获得焦点时,将评估该表达式,但不会调用该表达式.此外,您在双引号中嵌套了双引号,这会导致语法错误 ("yellow").那些需要改为单引号.

The first doesn't work because it is wrapped in parenthesis and therefore it is a function "expression", rather than a function "declaration". Expressions are meant to be "evaluated", so when your element gets the focus, the expression is evaluated, but not invoked. Also, you have double-quotes nested within double-quotes, which would cause a syntax error ("yellow"). Those would need to be changed to single quotes.

第二个有效,因为表达式"立即被第二组括号 (this) 调用.

The second works because the "expression" is immediately invoked by the second set of parenthesis (this).

但是,应避免使用这两种语法.不要使用内联 HTML 事件属性来连接事件处理回调函数,因为它们:

However, both syntaxes should be avoided. Don't use inline HTML event attributes to wire up event handling callback functions because they:

  • 创建难以阅读并导致重复的意大利面条式代码代码
  • 创建改变this 绑定的全局包装函数功能
  • 不要遵循 W3C DOM 事件 标准
  • create spaghetti code that is hard to read and leads to duplication of code
  • create global wrapper functions that alter the this binding in the function
  • don't follow the W3C DOM Event standard

相反,用 JavaScript 编写您的事件处理程序:

Instead, write your event handlers in JavaScript:

// Get a reference to the DOM element
var input = document.getElementById("inp");

// Wire up an event handler
input.addEventListener("focus", function(e){
  input.style.background ='yellow';
});

<input id="inp" type="text">

这篇关于调用与事件关联的匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆