2011-07-16 3 views
1

HTML:jQuery traversant en utilisant le plus proche

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

J'ai les deux fonctions pour afficher/masquer une tr. Le code que j'ai maintenant fonctionne, mais il fermera aussi d'autres éléments. Quelle est la manière élégante de faire ceci?

+0

Alors pourquoi n'utilisez-vous pas 'nearest'? Passer une fonction à 'document.ready' dans les fonctions est inutile. –

Répondre

1

Cela devrait le faire:

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, pour "élégant", retirez les onclick attributs du HTML!

Puis ajouter la fonctionnalité de clic avec:

$('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); 

à l'intérieur du $(document).ready().

0

Le sélecteur closest a été ajouté dans la version 1.3 je crois, donc il suffit d'utiliser cela.