jQuery在点击内覆盖.click事件

时间:2009-03-10 14:20:25

标签: jquery

我有这些功能:

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

和这个电话:

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

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

有谁知道如何覆盖项目的.click事件?我也试过了 $("#location-toggle-"+id).click(TargetWorksheet.toggle_child_locations(id)); 由于某种原因,它一直在递归地翻转。

思想?

1 个答案:

答案 0 :(得分:66)

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

在添加新元素之前,您可以使用$("#location-toggle-"+id). unbind()清除该元素的处理程序,它应该可以正常运行。

相关问题