2012-11-06 77 views
0

是否可以更改由現有的onmouseoveronmouseout事件調用的函數?對於下面的例子,我有一種方法可以讓ChangeItemAEvent將「ItemA」onmouseover函數從ChangeColor()更改爲ChangeColorBack()?目前我需要聲明一個全新的函數,我覺得它不夠優雅,因爲我應該能夠調用現有的函數時重複代碼。要更改onmouseover或onmouseout來調用其他函數的JavaScript?

的javascript:

function ChangeColor(elementid) 
{ 
    document.getElementById(elementid).style.background = "Orange"; 
    document.getElementById(elementid).style.color = "Black"; 
} 

function ChangeColorBack(elementid) 
{ 
    document.getElementById(elementid).style.background = "Black"; 
    document.getElementById(elementid).style.color = "White"; 
} 

function ChangeItemAEvent() 
{ 
    document.getElementById("ItemA").onmouseover = function() { 

    document.getElementById("ItemA").style.background = "Black"; 
    document.getElementById("ItemA").style.color = "White"; 

    }; 
} 

HTML:

<span id="ItemA" onmouseover="ChangeColor(this.id)"> 
<button id="ButtonB" onclick="ChangeItemAEvent()"> 

在此先感謝

回答

1

連接,而不是在標記中的JavaScript事件:

document.getElementById('ItemA').onmouseover = changeColorBack; 

注意大寫函數的n個名字通常作爲約定保留給構造函數。
然後在你的函數使用this這指的是被稱爲元素:

function changeColorBack() { 
    this.style.background = "Black"; 
    this.style.color = "White"; 
} 

現在,你可以通過它分配一個新的功能元素的事件或通過重寫功能使用任何元素這些函數之前設置。

+0

哦,不錯我addapted你剛纔所說的,現在這對我的作品。謝謝您的幫助! – Epik

0

另一種解決方案是創建一個toggleColor(elementId)功能:

function toggleColor(elementId) { 
    if (this.style.color == "White") { 
     this.style.background = "White"; 
     this.style.color = "Black"; 
    }else { 
     this.style.background = "Black"; 
     this.style.color = "White"; 
    } 
} 
+0

好,除了 - 使用elementId和這個變量表示一個未完成的函數。即,您永遠不會在elementId上調用document.getElementById - 也不會顯示函數被附加的方式,以使'this'關鍵字有用。 – enhzflep

0

聽起來像是你需要做登記事件的不同方法的一些閱讀。需要注意的是,有三種不同的方法用於在JavaScript中註冊事件。詳情請見https://developer.mozilla.org/en-US/docs/DOM/event。還要注意許多不同的JavaScript框架通過提供他們自己的方法來以跨瀏覽器兼容的方式註冊事件。

在您的示例中設置諸如此類事件<button id="ButtonB" onclick="ChangeItemAEvent()">之類的事件的方法不是建議事件的推薦方式。也不是設置元素的.onmouseover.onclick

我建議閱讀關於Mozilla事件的鏈接,如果您已經在使用JavaScript框架,請閱讀有關事件的文檔。

此外還有一個removeEventListener方法,你可能會或可能找不到有用的。

0

這個工作對我來說:

function overBtn(btncalling) { 
      document.getElementById(btncalling).style.backgroundColor = '#507CD1'; 
      document.getElementById(btncalling).style.color = 'White'; 
    } 

    function outBtn(btncalling) { 
      document.getElementById(btncalling).style.backgroundColor = 'White'; 
      document.getElementById(btncalling).style.color = '#507CD1'; 
    } 

相關問題