2012-03-05 83 views
0

我動態地插入一些用作按鈕的圖像並添加一個onClick事件。動態替換onclick處理程序

$("img.image_edit_customer").live("click", function() { 
    // when clicking the edit image of a row 
    $(this).manipulateCustomer("editRowCustomer", { 
     scope : "#customer_tbody" 
    }); 
}); 

後來我想從用作按鈕的圖像中刪除onClick事件。

$('img[class^="image_edit"]').live('click', function() { 
    // do nothing from now on 
    alert('edit'); 
}); 

現在,它始終執行舊新的處理程序。

UPDATE

如果我使用die('click');,我仍然可以執行onclick事件一次。

回答

1

的jQuery 1.7+

要附加只運行一次的事件和然後刪除本身:

$(document).one("click", "img.image_edit_customer", function() { 
    $(this).manipulateCustomer("editRowCustomer", { 
     scope : "#customer_tbody" 
    }); 
}); 

要附加,可以是除去在稍後的時間的事件:

$(document).on("click", "img.image_edit_customer", editRow); 

要刪除事件:

$(document).off("click", "img.image_edit_customer", editRow); 

功能連接和除去

function editRow(e) { 
    $(e.target).manipulateCustomer("editRowCustomer", { 
     scope : "#customer_tbody" 
    }); 
} 
+0

它也適用於動態插入的圖像嗎? – 2012-03-05 10:32:30

+0

是的,任何可以附加處理程序的元素都應該使用這種方法。它監聽文檔級別的任何「單擊」事件,只要目標元素的選擇器是正確的,它將起作用,但您應該嘗試使用比「文檔」更近的父級,這當然如果可能的話,不要動態地插入。 – adeneo 2012-03-05 10:50:06

0

由於您使用.live()你需要使用.die()方法來刪除事件處理程序綁定事件:

$('img[class^="image_edit"]').die('click'); 

注意

在jQuery 1.7中,建議使用而是使用.on().off()方法來附加和取消附加事件處理程序。

2

由於要連接現場法的事件,你需要使用模具方法

http://api.jquery.com/die/

+1

+1,'live'和'die'都被棄用t hought。 – fardjad 2012-03-05 08:40:33

+0

不用提這個 – 2012-03-05 08:44:35

0

而不是拆散或殺死(又名死亡)的所有匹配元素的事件,我會慶祝以「標記」類各個元件,像這樣:

$("img.image_edit_customer").live("click", function() { 
    if(!$(this).hasClass('clicked')) { 
     $(this).addClass('clicked'); 
     $(this).manipulateCustomer("editRowCustomer", { 
      scope : "#customer_tbody" 
     }); 
    } 
});