2011-07-16 86 views
1

HTML:的jQuery遍歷使用最接近

<table border="1px"> 
     <tr> 
      <td colspan="2"> 
       <div class="commentLink"> 
        <a onclick="ShowBox.call(this); return false;" href="#">Comment</a> 
       </div> 
      </td> 
     </tr> 
     <tr class="commentBox" style="display: none;"> 
      <td colspan="2"> 
       <div class="hiddenComment"> 
        <textarea class="textComment" rows="2" cols="100"></textarea> 
        <input class="foo" type="checkbox" /> 
        <input class="commentBtn" type="button" value="Submit" onclick="addComment.call(this); return false;" /> 
        <input class="commentBtn" type="button" value="Cancel" onclick="HideBox.call(this); return false;" /> 
       </div> 
      </td> 
     </tr> 
    </table> 

JS:使用jQuery 1.4.2

function ShowBox() { 
     var that = this; 
     $(function() { 
      $(".commentBox").show(); 
      //$(that).closest('tr').siblings().show(); 
     }); 
    } 
    function HideBox() { 
     var that = this; 
     $(function() { 
      $(that).siblings(".foo").attr("checked", false); 
      $(that).siblings(".textComment").empty(); 
      $(".commentBox").hide(); 
     }); 
    } 

我有兩個函數來顯示/隱藏TR。我現在的代碼有效,但它也會關閉其他元素。這樣做的優雅方式是什麼?

+0

那麼你爲什麼不使用「最接近」?將函數傳遞給函數內的'document.ready'是不必要的。 –

回答

1

這應做到:

function ShowBox() { 
    $(this).closest ('tr').next ('tr.commentBox').show(); 
} 

function HideBox() { 
    var jThis = $(this); 

    jThis.siblings(".foo").attr("checked", false); 
    jThis.siblings(".textComment").empty(); 
    jThis.closest ('tr.commentBox').hide(); 
} 


BTW,爲 「優雅」,請從HTML的onclick屬性!

$('td div.commentLink > a').bind ('click', ShowBox, false); 
$('td div.hiddenComment > a.commentBtn[value=Submit]').bind ('click', addComment, false); 
$('td div.hiddenComment > a.commentBtn[value=Cancel]').bind ('click', HideBox, false); 

$(document).ready()內:

然後添加點擊功能。

0

closest選擇器在版本1.3中添加我相信,所以只是使用它。