2012-03-03 49 views
0

這裏是我的表..我想清理jQuery,以便我可以在表格的html中的許多行上使用此邏輯。表中的jquery索引

<table>       
    <tr> 
     <td class="check"><input class="select_service3 user_checkbox" type="checkbox"></td> 
     <td class="name">NAME</td> 
     <td class="duration"> 
      <span class="duration3">30 min</span> 
      <a class="custom_duration_link3">Custom</a> 
      <span class="custom_duration_input3"><input class="custom" type="text"> min <button class="custom_duration_save3">Save</button></span> 
     </td> 
     <td class="price">$25 <a class="custom_price_link3">Custom</a></td> 
    </tr> 
</table> 

jQuery的

$(".custom_duration_link3").hide(); 
    $(".custom_price_link3").hide(); 
    $(".custom_duration_input3").hide(); 

    $(".select_service3").click(function(){ 

    if ($(".select_service3").is(":checked")) 
    { 
     $(this).closest("tr").addClass("active"); 
     $(".custom_duration_link3").show(); 
     $(".custom_price_link3").show(); 

     $('.custom_duration_link3').click(function(){ 
      $('.custom_duration_link3').hide(); 
      $('.duration3').hide(); 
      $('.custom_duration_input3').show(); 
     }); 

     $('.custom_duration_save3').click(function(){ 
      $('.custom_duration_input3').hide(); 
      $('.duration3').show(); 
      $('.duration3').addClass("notused"); 
     }); 

    } 
    else 
    { 
     $(this).closest("tr").removeClass("active"); 
     $('.custom_duration_link3').hide(); 
     $('.custom_duration_input3').hide(); 
     $('.duration3').show(); 
     $('.duration3').removeClass("notused"); 
     $('.custom_price_link3').hide(); 
    } 
    }); 

我做什麼的來收拾這個代碼,而不必做 「.duration1" ,」 .duartion2" ,等等

感謝您的幫助。

回答

2

基本上,使用函數中的this對象來檢索活動行。然後只在該行的範圍內引用類名。這裏有一個快速演示:

http://jsfiddle.net/znxQk/

的想法是利用這樣的:

var current = $(this).closest("tr"); 
$(".custom_price_link",current).show(); 
+0

@Josh歡迎您。很高興我能幫上忙。 :) – 2012-03-03 08:59:17

1

我知道你有你的答案,但如果你不想手動指定選擇和他們的未來的位置將會一樣,那麼你可以這樣做。

if ($(".select_service3").is(":checked")) 
    { 
     $(this).closest("tr").addClass("active"); 
     $(this).parent() 
      .siblings('.duration').children(':not(:last)').show().end() 
      .children('a').click(function() { 
       $(this).parent() 
        .children().hide().end() 
        .children(':last').show() 
        .children('button').click(function() { 
         $(this).parent().hide().parent().children(':first').addClass('notused').show(); 
        }); 
      }).end() 
      .siblings(':last').children('a').show(); 
    } 
    else 
    { 
     $(this).closest("tr").removeClass("active"); 
     $(this).parent() 
      .siblings('.price').children('a').hide().end() 
      .siblings('.duration').children(':first').removeClass('notused').show().end() 
      .children(':not(;first)').hide(); 
    } 

演示:http://jsfiddle.net/92cMj/