简体   繁体   中英

Question about Javascript onmouseover

I am very new to Javascript and was wondering why the following code will not work.

var p = document.createElement("p");
p.onmouseover = (function() {
    this.style.cursor='pointer';
})();

Basically, I just want the cursor to change to pointer when the user hovers over this dynamically create paragraph element.

Thank you.

You are invoking the function by putting () at the end. Try this instead:

var p = document.createElement("p");
p.innerHTML = 'Hello World';
p.onmouseover = function() {
    this.style.cursor = 'pointer';
};  
document.body.appendChild(p);

and here's a working demo .

Two reasons;

1. You haven't attached the element to the document .

You need to do something like below in order for the event handlers to be registered:

document.documentElement.appendChild(p);


2. You need to only define the function. You are defining it and then immediately invoking it with the (function { ... })() syntax. You should just define it, eg

p.onmouseover = function () {
    this.style.cursor = "pointer";
}

First you do not need the closure.

var p = document.createElement("p");
p.onmouseover = function() {
    this.style.cursor='pointer';
};

IMO a better way to do this is to use CSS for what it's good at

<style>
p {cursor:pointer;}
</style>

Have you considered using a CSS style rather than setting it in code? It's often handy to keep the visual aspects of the page separate to the programming in case you need to tweak the presentation later...

<style type="text/css">
.myStyle {cursor:pointer;}
</style>

The javascript would become:

this.setAttribute("class", "myStyle");

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM