2015-04-27 66 views
1

我有一個表格。每列在頂部都有一個按鈕。如果列中的以下td元素中有內容,則隱藏該按鈕。如果沒有,那麼顯示按鈕和onClick添加類活動太td元素。如果表格元素上滿足條件,則進行切換

$(document).ready(function(){ 
    $('.button-fill').on("click", function() { 
     var i=$(this).parent().index(); 

     if($(this).closest("tr").siblings().find("td:eq("+i+")").text()=="") 
      $(this).hide(); 
     else 
      $(this).show();  
    }); 

<!-- Fill in the td --> 
    $('.button-fill').on("click", function() { 
     var i=$(this).parent().index(); 
     $(this).closest("tr").siblings().find("td:eq("+i+")").addClass("active"); 
     //}); 
    }); 
}); 

http://jsfiddle.net/ujw0u6au/

我創建了一個的jsfiddle。我不知道我做錯了什麼?謝謝

+0

嗨,你的要求我不清楚。如果任何一列的文本比最初的文字不想顯示「填充」按鈕?並且如果用戶點擊「填寫」按鈕,您將分配所有TD「活動」類?我對麼? – Prateek

回答

2

由於您已經綁定了按鈕點擊中的按鈕切換邏輯 - 您將始終在起始位置有按鈕。當你點擊按鈕時,它將首先隱藏該按鈕,然後製作內容active

如果您想這種行爲在儘快開始在網頁加載,你應該(在你的代碼中的2號線)從您的代碼更改如下行 -

$('.button-fill').on("click", function() {

$('.button-fill').each(function(i,e) {

此外,您不應該在JavaScript中使用<!-- Fill in the td -->註釋風格。

0

我可以看到你在同一個類上有兩個「單擊」事件處理程序。而不是它,你也可以合併它。

這裏是你的代碼的優化版本:

的JavaScript:

$(document).ready(function(){ 
    $('.button-fill').on("click", function() { //Only one click event handler 
     var $this = $(this); 
     var i=$this.parent().index(); 
     var $trSibling = $this.closest("tr").siblings(); 
     $this.toggle($trSibling.find("td:eq("+i+")").addClass("active").text() != ""); //adds the class as well and check the text as well.  
    }) 
    $(".button-fill").trigger("click"); 
    // explicitly clicking on button to make sure that initially button should not be shown if column text is not empty 
}); 

的jsfiddle鏈接:http://jsfiddle.net/ujw0u6au/1/

這是你想要的一樣嗎?

0

@Vijay有正確的答案,但作爲一個側面說明,你需要改變這一點:

if($(this).closest("tr").siblings().find("td:eq("+i+")").text()=="") 

這個

if($(this).closest("tr").siblings().find("td:eq("+i+")").text()!="") 

,如果你要隱藏的按鈕時,有內容,而不是其他方式(注意接近結束處的!=)。

相關問題