“this” keyword doesn’t seem to work

落爺英雄遲暮 提交于 2019-12-05 10:36:45

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>

You function click doesn't know about 'this'. Change it to:

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

and

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

Your question seems to be about the value of this. In an inline handler, this will represent the window. You can set the value of this using .call(), so it gives the value you desire.

Example: http://jsfiddle.net/patrick_dw/5uJ54/

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

Now in your click method, this will be the <button> element.

The reason is that your inline attribute gets wrapped in a function, which itself has the context of the element. But it doesn't actually call your function from that context. By doing click(), it ends up looking like:

function onclick(event) { 
    click();
}

Your function is being called against no particular object, so the window is implied. By doing:

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

...you end up with:

function onclick(event) { 
    click.call( this );
}

Giving the desired context. You can also pass the event object:

<button id="clicker" onclick="click.call( this, event )" >Click me</button>

...so you end up with:

function onclick(event) { 
    click.call( this, event );
}

So now in your click() function, you'll have the event as you'd expect.

Also, you may have issues with using click as a function name. I'd change it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!