2012-07-09 43 views
0

我有一個功能,通過點擊它包含在< thead>標記中的標題隱藏/顯示錶。點擊時,表格隱藏,剩下的只是標題,通過再次點擊可以取消隱藏表格。Javascript/jquery:無法指定表中的兄弟節點

我有多個表,並且只想使用函數,而不是爲每個表編寫一個表。爲了做到這一點,我試圖傳遞參數(this,this.lastSibling)。由於某種原因,this.lastSibling沒有針對任何對象。我試過了所有可以想到的節點樹的導航方式,但我無法定位到tbody。

我的JavaScript/jQuery的

function ToggleTable(trigger,target){ 
    $(trigger).click(function(){ 
     $(target).toggle(); 
     ToggleTable(trigger,target) 
    }); 
} 

我的HTML

<table class="format2" > 
    <thead onmouseover="ToggleTable(this,this.lastSibling)"> 
     <!--Title--> 
    </thead> 
    <tbody> 
     <!--Cells with information in here--> 
    </tbody> 
    <!--Note No TFooter Tag--> 
</table> 

<--Other tables similar to the one above--> 

提前感謝!

+0

http://stackoverflow.com/questions/2681581/jquery-how-do-i-check-if-an-element-is-the-last-sibling – zod 2012-07-09 18:59:16

+0

http://stackoverflow.com/questions/2126512/last jquery – zod 2012-07-09 18:59:34

回答

0

我有一個隱藏/功能顯示錶通過點擊它包含在一個<thead>標記它的頭。點擊時,表格隱藏,剩下的只是標題,通過再次點擊可以取消隱藏表格。

我迷失在你當前的代碼中。但是,如果你想切換TBODY在你<table>標籤的可見性(或最後一個子元素,你可以試試這個

function ready() { 

    $('table > thead') 
    .each(function(e){ 
     $(this).siblings(':last').hide(); 
    }) 
    .click(function(e) { 
     $(this).siblings(':last').toggle(); 
    }); 

} 

$(ready); 

活樣本:http://bl.ocks.org/3078240

0

假設您的所有表都將具有類format2。 試試這個:

$("table.format2 > thead").click(function(){ 
    $(this).next("tbody").toggle(); 
}); 

的jsfiddle:http://jsfiddle.net/KcY4X/

+0

不行。它仍然不能以<'tbody'> $(「table.format2> thead」)。click(function(){(this).next(「tbody」)。toggle()' }); – 2012-07-09 19:05:07

+0

@AlexiaHurley修正了錯別字。與JSFiddle一起檢查更新 – Chandu 2012-07-09 19:51:41

0

如果你想嘗試的解決方案利用核心JavaScript而不是jQuery shims,這可能對你有用,這是我很快寫的一個函數,它返回的是HTML元素的最後一個兄弟(例如不是文本節點),儘管你應該能夠輕鬆修改它以接受任何節點在DOM中:

function getLastSibling(el) { 
    var siblings, x, sib; 

    siblings = el.parentNode.children; 
    x = siblings.length; 

    while ((sib = siblings[x - 1]) && x >= 0) { 
     console.log(sib); 
     console.log(sib.nodeType); 
     if (sib.nodeType != 1 || sib.tagName == 'SCRIPT') { 
      x--; 
     } else { 
      return sib; 
     } 
    } 

    return null; 
}