I'm a newbie on JS and I don't understand yet how to use "this" keyword.
Here is a simple html, and I want, for example, the div
and the p
elements to get a green border onmouseover with a JS function using this
keyword or something else to make the function work on both or maybe any html element.
<div id="firstDiv" onmouseover="greenBorder()">
<h1>I'm Bruce</h1>
</div>
<p id="firstP" onmouseover="greenBorder()"> I'm Batman </p>
And I know it's not correct but my JS code would be like:
function greenBorder(){
this.style.border="1px solid green";
Thank you
this
is set upon the invocation of a function. In this case your inline code is called like a function with this
set to the element, but when you call greenBorder
, its this
is unset.
(If you were calling a property of an object, eg myObject.myMethod()
, then the this
would be set to the object myObject
instead. Otherwise, it is window
or, if your JavaScript code runs in strict mode, undefined
.)
You can either explicitely set its this
, using the .call
method:
<p id="firstP" onmouseover="greenBorder.call(this)"> I'm Batman </p>
... this way, the code you posted will work as-is:
function greenBorder () {
this.style.border = "1px solid green"
}
Or, you can pass in the element as an argument:
<p id="firstP" onmouseover="greenBorder(this)"> I'm Batman </p>
In the latter case you'd have to change your function to use the argument instead of this
:
function greenBorder (element) {
element.style.border = "1px solid green"
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.