“这个”关键字似乎不起作用 [英] “this” keyword doesn’t seem to work

查看:93
本文介绍了“这个”关键字似乎不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想了解这个关键字在JavaScript中的工作方式,并且我制作了这个脚本:

 函数click(){
this.innerHTML =changed;
}

用于这个HTML:

 < button id =clickeronclick =click()>点击我< /按钮> 

但它不起作用,任何人都可以解释为什么?
<这个只存在于 onclick 的范围内。 事件本身。它不会自动绑定到其他函数。



传递它像这样:

  function click(element){
element.innerHTML =changed;
}

和html:

 < button id =clickeronclick =click(this)>点击我< / button> 


I am trying to understand how the this keyword works in JavaScript and I made this script:

function click(){
    this.innerHTML="changed";
}

Used in this HTML:

<button id="clicker" onclick="click()" >Click me</button> 

But it doesn't work, can anyone explain why?

解决方案

this exists only in the scope of the onclick event itself. It is not bound automatically to other functions.

Pass it on like this:

function click(element){
element.innerHTML="changed";
}

and the html:

<button id="clicker" onclick="click(this)" >Click me</button>

这篇关于“这个”关键字似乎不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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