2012-05-08 70 views
-1

我的代碼:如何使用類名隱藏DIV?

var array1 = document.getElementsByClassName("div"); 
var array2 = document.getElementsByClassName("button"); 

    for(var i = 0; i < array1.length; i++) 
    { 
     $(array2[i]).show(); 
     $(array1[i]).hide(); 

     $(array2[i]).click(function(){ 
      $(array1[i]).slideToggle(); 
     }); 
    } 

爲什麼我得到錯誤: 無法轉換的JavaScript參數arg 0?

+1

發佈[JS小提琴](http://jsfiddle.net/),或類似的,演示。否則,你不可能得到一個好的答案,因爲我們不能看到你有什麼問題。 –

+2

你是不是指'getElementsByTagName'?因爲'div'和'buttons'是HTML中的標準標籤。不上課。 –

+1

你很明顯使用jQuery,你爲什麼混合? –

回答

4
var $buttons = $(".button").hide(); 

$(".div").show().bind("click", function(event) { 
    var index = $divs.index(this); 

    $buttons.eq(index).slideToggle(); 
}); 

OR:

var $buttons = $(".button").hide(), 
    $divs = $(".div").show(); 

$.each($buttons, function(index) { 
    var $button = $(this); 
    $divs.eq(index).bind("click", function() { 
     $button.slideToggle(); 
    }); 
}); 

OR

var $buttons = $(".button").hide(), 
    $divs = $(".div").show(); 

$buttons.each(function(index) { 
    var $button = $(this); 
    $divs.eq(index).bind("click", function() { 
     $button.slideToggle(); 
    }); 
}); 
+0

@Truth。謝謝你的className修復。 – andlrc

+0

我不介意提出這個問題,因爲你已經實施了我的建議。 –

+0

我相信你不正確地使用index(),它應該是$('。div')。index($(this)); –