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

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

问题描述

以下代码不起作用

<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 ?

推荐答案

第一个不起作用,因为它包含在括号中,因此它是一个函数表达式,而不是一个函数声明。表达式意味着被评估,所以当你的元素得到焦点时,表达式被计算,但不被调用。另外,你有双引号嵌套在双引号中,这将导致语法错误(黄色)。这些都需要更改为单引号。

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.

第二个是有效的,因为expression立即被第二组括号(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:


  • 创建难以阅读的spaghetti代码并导致重复
    代码

  • 创建全局包装函数,改变
    函数中的 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天全站免登陆