2011-04-10 44 views
1

我對JavaScript很陌生,想知道爲什麼下面的代碼不起作用。關於Javascript onmouseover的問題

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

基本上,我只是希望遊標改變爲指針,當用戶懸停在此動態創建段落元素。

謝謝。

回答

3

您正在調用該功能,將()放在最後。試試這個:

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

這裏是一個working demo

+0

非常感謝你。 – noob 2011-04-10 16:51:03

0

首先你不需要關閉。

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

有兩個原因;

1.您尚未將此元素附加到document

你需要做類似下面爲了要註冊的事件處理程序:

document.documentElement.appendChild(p); 


2.您只需要定義函數。您正在定義它,然後立即用(function { ... })()語法調用它。您應該定義它,例如

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

IMO更好的方式來做到這一點是使用CSS它所擅長

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

您使用CSS樣式,而不是在代碼中設置它考慮?這往往得心應手保持頁面分開來的情況下,你需要的演示文稿後,來調整節目的視覺方面...

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

的JavaScript將成爲:

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