1

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()');
}

あまり良くありませんが、今のところは機能します。より良い解決策はありますか?

4

2 に答える 2

1

考えられる解決策の 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);
于 2012-12-23T21:39:55.370 に答える
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); 
}
于 2012-12-23T22:09:06.990 に答える