簡體   English   中英

jQuery click事件僅在<tr>

[英]JQuery click event works only once in a <tr>

我如何才能使此點擊在我的html中只起作用一次?

現在,它在表中的所有tr中都有效,此后應該只工作一次。

$("#example tbody tr").on("click", function() {
   $(this).addClass('row-selected');            
})

首次單擊后,您需要取消綁定click事件:

 var tr = $("tr"); tr.one("click", function() { // this means that you can only click each row once $(this).toggleClass('row-selected'); tr.off('click'); // this will unbind the click event from the rest of the rows }) 
 .row-selected td { font-weight: bold; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td>one</td> </tr> <tr> <td>one</td> </tr> <tr> <td>one</td> </tr> <tr> <td>one</td> </tr> <tr> <td>one</td> </tr> <tr> <td>one</td> </tr> </table> 

試着用one ,而不是on 有關one http://api.jquery.com/one/的更多信息

("#example tbody tr").one("click", function() {
   $(this).addClass('row-selected');            
})

嘗試這個。

$("#example tbody tr").one("click", function() {
   $(this).addClass('row-selected');            
})

在click事件回調中,您可以刪除事件。 只需將事件作為參數傳遞即可。

$("#example tbody tr").on("click", function(event) {
   $(this).addClass('row-selected'); 
   event.target.onclick = null;
})
// Try This
jQuery(document).ready(function(){
 $(document.body).on("click", '#example tbody tr', function() {
  $(this).addClass('row-selected');            
 });
});

嘗試將on(“ click”更改為one(“ click”

試試下面

$("#example tbody tr").one("click", function() {
$(this).addClass('row-selected');            
})code here

或者您可以嘗試簽出此頁面綁定取消綁定

這是他們在我鏈接的該網站上使用的示例。

$('#my-selector').bind('click', function() {
   $(this).unbind('click');
   alert('Clicked and unbound!');
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM