【问题标题】:Javascript onclick bject dependent methodJavascript onclick对象依赖方法
【发布时间】:2012-12-23 21:31:35
【问题描述】:

我得到了一张切换 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()');
}

不是很好,但它暂时有效。有更好的解决方案吗?

【问题讨论】:

    标签: javascript object methods onclick


    【解决方案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);
    

    【讨论】:

      【解决方案2】:

      你可以试试这个

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

      【讨论】:

        猜你喜欢
        • 2011-01-24
        • 1970-01-01
        • 1970-01-01
        • 2011-06-29
        • 1970-01-01
        • 1970-01-01
        • 2020-03-24
        • 2023-03-12
        • 2020-04-06
        相关资源
        最近更新 更多