2017-02-15 52 views
0

中只能運行一次我怎樣才能讓這個點擊只在我的html中工作一次?JQuery點擊事件只能在<tr>

現在它工作在桌子的所有tr上,應該在此之後再工作一次。

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

更改'。對()''來。一()' – j08691

+0

你想點擊每行還是隻需點擊一下表格?如果是後者,那麼'.one'將不起作用,您將需要解除其餘的點擊(請參閱下面的答案) – Pete

回答

4

您將需要先點擊後解除綁定單擊事件:

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>

0

試試這個。

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

嘗試用one而不是on。更多關於onehttp://api.jquery.com/one/

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

裏面點擊事件的回調,你可以刪除事件。只需將事件作爲參數傳遞即可。

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

嘗試改變的( 「點擊」 一個( 「點擊」

試試下面

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

,或者你可以嘗試檢查了這個頁面bind unbind

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

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

綁定和解除綁定在v3中不推薦使用 - 使用on和off – Pete