JavaScript事件处理程序参数 [英] JavaScript event handler arguments

查看:116
本文介绍了JavaScript事件处理程序参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下JavaScript代码:

I have the following JavaScript code:

var ans_el = document.createElement( 'input' );
ans_el.setAttribute( 'id', unique_int_value );
ans_el.setAttribute( 'type', 'radio' );
ans_el.setAttribute( 'name', 'group' );
ans_el.setAttribute( 'value', 'myValue' );
ans_el.onclick = myFunction( this.id, this.value ); 

// Add ans_el to DOM.

function myFunction( index, value ) { // do something }

当然,这不符合预期。至少在Firefox 3.6中没有。当创建元素并且传递给 myFunction 的参数为null时,会触发 onclick 事件。将元素添加到DOM后,选择单选按钮时不会触发 onclick 事件。

This, of course, does not work as expected. At least not in Firefox 3.6. What happens is the onclick event is fired when the element is created and the arguments passed to myFunction are null. After the element is added to the DOM, the onclick event does not fire when the radio button is select.

如果有人能够深入了解这里发生的事情,和/或如何动态添加事件处理程序,我将不胜感激。

I'd be grateful if anyone has some insight into what's happening here, and/or how dynamically adding event handlers can be accomplished.

推荐答案

您需要为onclick提供一个函数的引用;您当前正在执行该函数并将该结果分配给onclick处理程序。这更接近你想要的:

You need to give a reference to a function for onclick; you are currently executing the function and assigning that result to the onclick handler. This is closer to what you want:

ans_el.onclick = function(e) {
   myFunction(ans_el.id, ans_el.value);
};

更新:决定使用event.target作为一个更清晰的例子,因为Andir提出了它。

UPDATED: Decided to use event.target for a clearer example since Andir brought it up.

ans_el.onclick = function(e) {
   myFunction(e.target.id, e.target.value);
};

这篇关于JavaScript事件处理程序参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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