2012-03-16 18 views
-1

這是當前的代碼中使用的.next():如何通過幾個要素

$("input[name='content_use']").click(function() { 
    if ($(this).is(":checked")){ 
     $(this).closest('tr').next().show(); 
     $(this).closest('tr').next().next().show(); 
     $(this).closest('tr').next().next().next().show(); 
    } else{ 
     $(this).closest('tr').next().hide(); 
     $(this).closest('tr').next().next().hide(); 
     $(this).closest('tr').next().next().next().hide(); 
    } 
}); 

:|

編輯:

正如你看到的,我必須使用next()多次達到連續的行。我如何編碼這個更短?


解決方案nextUntil()由於@pimvdb

+4

吧?再試一次......你想問什麼? – 2012-03-16 21:15:01

+0

你的標記是什麼? 'nextUntil'可能是解決方案。請致電 – pimvdb 2012-03-16 21:15:36

+0

。這很明顯... – 2012-03-16 21:15:42

回答

1

使用.nextAll「讓每一個元素的所有兄弟姐妹之後在匹配的元素集合的」

$("input[name='content_use']").click(function() { 
    if (this.checked) { 
     $(this).closest('tr').nextAll().show(); 
    } else { 
     $(this).closest('tr').nextAll().hide(); 
    } 
}); 
+1

不妨使用'.toggle(bool)'。 – pimvdb 2012-03-16 21:20:12

+0

@pimvdb使用**'$(this).closest('tr')。nextAll()。toggle(this.checked)'**當然會是一個更好的解決方案,前提是'show'和'hide'是隻有函數中的方法 - 文檔:http://api.jquery.com/toggle/ – 2012-03-16 21:21:31

+0

看起來不錯,但我不想到達所有兄弟行,只是2,3或4. – 2012-03-16 21:22:40