2011-05-10 24 views
1
$('#historie .accordion_toggler .content').toggle(); 
for (i=0; i<3; i++) { 
    $('#historie .accordion_toggler .content')[i].toggle(); 
    $('#historie .accordion_toggler .head')[i].toggleClass('active'); 
} 

使用此代碼我收到此錯誤:「對象不支持此屬性或方法。」JavaScript/jQuery:IE中的對象存在問題

我的目標是關閉所有元素,但再次打開前三個元素。

任何想法?

+0

您可以張貼演示,在[JS提琴(HTTP://的jsfiddle。網/),顯示你到目前爲止? – 2011-05-10 16:08:55

回答

0

我想你可能會調用DOM元素本身的方法。嘗試一個襯墊這樣的:

$('#historie .accordion_toggler .content').toggle().slice(0,3).toggle().toggleClass('active') 
0

試試這個,只是爲了確保你只能得到存在的元素,並更新了jQuery元素不是原生的DOM元素(eq()):

$('#historie .accordion_toggler .content').toggle(); 

var go_until = $('#historie .accordion_toggler .content').length; 
if($('#historie .accordion_toggler .head').length < go_until){ 
    go_until = $('#historie .accordion_toggler .head').length; 
} 

for (var i = 0; i < go_until; i++) { 
    // ANOTHER CHANGE HERE, that way you get the jQuery element 
    // and not the DOM element: 
    $('#historie .accordion_toggler .content').eq(i).toggle(); 
    $('#historie .accordion_toggler .head').eq(i).toggleClass('active'); 
} 
2

你得到錯誤的原因是因爲數組中的元素不是jQuery對象,所以他們沒有切換方法。

$('#historie .accordion_toggler .content')[i].toggle(); 

這應該工作:

$($('#historie .accordion_toggler .content')[i]).toggle(); 

但這是短:

$('#historie .accordion_toggler .content:lt(3)').toggle(); 
$('#historie .accordion_toggler .head:lt(3)').toggleClass('active'); 

有可能是,即使你向我們展示一個完整的例子更簡單的方法。

0

您是否只有三個元素,或者只有前三個元素需要切換?

你可以這樣做:

$('#historie .accordion_toggler .content').each(function(){ 
    $('this').toggle().toggleClass('active'); 
}); 

僅前3,你可以做到這一點

$('#historie .accordion_toggler .content').each(function(i){ 
    if(i < 3) 
     $('this').toggle().toggleClass('active'); 
});