2012-03-03 28 views
0

ここに私のテーブルがあります。テーブルのhtmlの多くの行でこのロジックを使用できるようにjqueryをクリーンアップします。jquery index in table

<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

。お役に立てて嬉しいです。 :) –

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(); 
    } 

デモ:どういたしまして@Josh http://jsfiddle.net/92cMj/