2012-12-23 58 views
1

我收到了一個切換onclick函數的圖像。被調用的函數是一個對象的方法。 我的問題:我不知道對象的名稱,所以我怎麼能Javascript onclick依賴於對象的方法

初始HTML代碼:

<img id="someID" [...] onClick="someObject.aFunction();" /> 

結果想:

<img id="someID" [...] onClick="someObject.otherFunction();" /> 

我目前使用Javascript(解決方法) :

someClass.prototype.aFunction() = function() { 
    button = document.getElementByID('someID'); 
    button.setAttribute("onclick", button.getAttribute('onclick').split('.')[0]+'.otherFunction()'); 
} 

不是很好,但它現在的作品。有更好的解決方案

回答

1

這裏是一個可能的解決方案:

var el = document.getElementById('someID'); 
el.onclick = function(){ 
    // or some other prop 
    if(el.hasBeenClicked) 
     function1(); 
    else 
     function2(); 

    // toggle the selected state 
    el.hasBeenClicked= !el.hasBeenClicked; 
} 

當然,也有很多(更好的)解決方案。
如果使用jQuery的,不是代碼應該被翻譯成類似:

$('#someID').toggle(function1, function2); 
0

你可以試試這個

someObject.doFunction = function() { 
    if (this.currentFunction == this.aFunction) 
     this.currentFunction = this.otherFunction; 
    else 
     this.currentFunction = this.aFunction; 
    this.currentFunction(); 
} 

function h() { someObject.doFunction()} 

var el = document.getElementById('someID'); 
if (el.attachEvent) { 
    el.attachEvent("onclick", h); 
} else { 
    el.addEventListener("click", h, false); 
}