jQuery 在点击中覆盖 .click 事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/630434/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:29:03  来源:igfitidea点击:

jQuery overwrite .click event within click

jquery

提问by brad

I have these functions:

我有这些功能:

TargetWorksheet.toggle_child_locations = function(id){
  $("#location-children-"+id).slideToggle("slow"); 
}

TargetWorksheet.get_child_locations = function(id, lvl){
  //Ajax grab all children and targets, and display children
  $.get('child_locations',{ location_id: id, level: lvl}, function(data){
    $("#location-children-"+id).append(data);
    TargetWorksheet.toggle_child_locations(id);
  });

  //Change onClick to just toggle since child data will now be loaded
  $("#location-toggle-"+id).click(function(){
    TargetWorksheet.toggle_child_locations(id);
  });
}

and this call:

这个电话:

$(function(){
  TargetWorksheet.toggle_child_locations(2);
  $("#location-toggle-2").click(function(){
    TargetWorksheet.get_child_locations(2,1);
  });
});

So I attach a click event to my '+' link (#location-toggle-2), which toggles child data. On first click, I want to do an ajax call to retrieve the child data, but then i just want to overwrite the .click on the #location-toggle-2 so that it now just toggles, and doesn't make the ajax call. The above code doesn't work, it doesn't seem to overwrite the .click, and makes the ajax call each time.

所以我将一个点击事件附加到我的“+”链接(#location-toggle-2),它切换子数据。在第一次点击时,我想做一个 ajax 调用来检索子数据,但后来我只想覆盖 #location-toggle-2 上的 .click 以便它现在只是切换,而不是进行 ajax 调用. 上面的代码不起作用,它似乎没有覆盖.click,并且每次都进行ajax调用。

Does anyone know how I can overwrite the .click event of an item? I also tried $("#location-toggle-"+id).click(TargetWorksheet.toggle_child_locations(id));And it just kept toggling over and over recursively for some reason.

有谁知道我如何覆盖项目的 .click 事件?我也试过 $("#location-toggle-"+id).click(TargetWorksheet.toggle_child_locations(id));它只是因为某种原因反复地反复切换。

Thoughts?

想法?

回答by Dave Ward

The only thing you're missing there is that using .click()addsa new handler every time it's called, not overwrites an existing one.

您唯一缺少的是 using每次调用时都会添加一个新的处理程序,而不是覆盖现有的处理程序。.click()

You can use $("#location-toggle-"+id).unbind()to clear handlers on that element before adding the new one, and it should work as you expect.

您可以$("#location-toggle-"+id).unbind()在添加新元素之前使用清除该元素上的处理程序,它应该按您的预期工作。