在第一次单击后更改元素的onclick处理程序

Changing onclick handler for an element after first click

本文关键字:onclick 处理 程序 元素 第一次 单击      更新时间:2023-09-26
   div.onclick = function(data, dom) {
        return function() {
           if (data.seenAlready == true) { // HACK
              $(this).children().toggle();
              return;
           }
           recursiveSearch(data, dom);
          // after this onclick, I want to assign it to a toggle like function. no clue how to do it.
       }
  }(child, mycontainer.appendChild(div));

我试图在对dom元素进行第一次onclick之后交换onclick方法。我只是没有取得任何成功,这似乎是某种关闭损失,或者其他什么。我可以使用jQuery。

有两种方法可以做到这一点,两种方法都是使用jQuery函数:

1( 使用one API方法-这将只工作一次。你会点击它一次,然后选择你自己的第二个处理程序,第一个不会再次开火,例如

$(myselector).one(function(){
    $(this).click(myotherhandler);
});

这是这个API的链接http://api.jquery.com/one/.

2( 您可以选择以下方式来替换事件处理程序。

$(myselector).click(function(){
    $(this).off();
    $(this).click("secondhandler");
});

这将关闭第一个处理程序,并只启动第二个处理程序

检查此jsbin:

http://jsbin.com/fekuq/1/edit?html,js,输出