将“this”传递给onclick事件 [英] Passing 'this' to an onclick event

查看:114
本文介绍了将“this”传递给onclick事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

当前元素作为其Event函数参数

这项工作是否可行

Would this work

<script type="text/javascript">
var foo = function(param)
{
    param.innerHTML = "Not a button";
};
</script>
<button onclick="foo(this)" id="bar">Button</button>

而非此?

rather than this?

<script type="text/javascript">
var foo = function()
{
    document.getElementId("bar").innerHTML = "Not a button";
};
</script>
<button onclick="foo()" id="bar">Button</button>

第一种方法是否允许我从其他位置加载JavaScript以对任何页面元素执行操作?

And would the first method allow me to load the javascript from elsewhere to perform actions on any page element?

推荐答案

您拥有的代码可以工作,但会从全局上下文执行,这意味着这个引用全局对象。

The code that you have would work, but is executed from the global context, which means that this refers to the global object.

<script type="text/javascript">
var foo = function(param) {
    param.innerHTML = "Not a button";
};
</script>
<button onclick="foo(this)" id="bar">Button</button>

您也可以使用非内联替代方法,该内联替代方法附加到特定元素上下文并从其执行允许您从这个中访问元素。

You can also use the non-inline alternative, which attached to and executed from the specific element context which allows you to access the element from this.

<script type="text/javascript">
document.getElementById('bar').onclick = function() {
    this.innerHTML = "Not a button";
};
</script>
<button id="bar">Button</button>

这篇关于将“this”传递给onclick事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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