2016-09-25 4 views
1

この関数は、HTMLのボタンを非表示にするには、CSSの.hidden属性を指定します。私は[0,1,2,3,4]を試しましたが、想定通りに動作しません。このコードは動作しますが、それを行うより効率的な方法があるのだろうかと疑問に思っていました。array内のすべての項目を一度に選択してクラスを追加する方法

function hideButtons(){ 
var buttons = document.querySelectorAll('.buttons'); 
    buttons[0].classList.add('hidden'); 
    buttons[1].classList.add('hidden'); 
    buttons[2].classList.add('hidden'); 
    buttons[3].classList.add('hidden'); 
    buttons[4].classList.add('hidden'); 
} 

答えて

2

使用単純なループを

for(var i = 0; i < buttons.length; i++){ 
    buttons[i].classList.add('hidden'); 
} 
0
$('.buttons').addClass('hidden'); 
+0

私はquerySelectorを使用しているので、この特定のケースではjqueryを使用していません – Joe

+1

jqueryを使用していると思われるので、 "jquery-selector"というタグを追加しました。 – ElChupacabra

0

これを試してみてください、それはあなたがあなたの入札を行うにはjQueryを使用することができソリューション

$('.buttons').hide(); 
0

少し簡単です:

$('selector').addClass('class_name'); 
0

これを行う最も簡単な方法はjQueryです。 jQueryのクラスセレクタは、ドキュメント上のすべての要素にマークを付け、一度にそれらに対してアクションを実行します。

あなたの関数は次のようになります。これを行うには

function hideButtons() { 
    $('.buttons').addClass('hidden'); 
} 

しかしれる好ましい方法をjQueryの機能hide()代わりのaddClassを(「隠された」)使用されるだろう。

1

配列全体を反復処理する必要がある方法にかかわらず、すべての配列要素に一度にクラスを追加することはできません。幸いにも、JavaScriptには配列を反復処理するいくつかの方法があります。

あなたはES6を使うことができるしている場合は、あなたがArray.from()へのアクセス権を持って、そして次のように使用することができアロー機能、:

function hideButtons(){ 

    // document.querySelectorAll() retrieves all elements 
    // matching the supplied CSS selector, and returns 
    // a non-live NodeList: 
    var buttons = document.querySelectorAll('.buttons'); 

    // Array.from() converts the supplied Array-like object 
    // into an Array, enabling the use of Array methods: 
    Array.from(buttons) 

    // here button represents the current element 
    // of the Array of buttons over which we're iterating, 
    // the expression following the fat arrow ('=>') 
    // is executed on each iteration, and adds the 'hidden' 
    // class-name to each element of the Array: 
    .forEach(button => button.addClass('hidden'); 
} 

ES6がなければ、あなたは次のようで上記の動作を再作成することができます:

function hideButtons(){ 
    var buttons = document.querySelectorAll('.buttons'), 

     // here we use Function.prototype.call() to allow 
     // us to apply the Array.prototype.slice to the 
     // NodeList, creating an Array from the NodeList: 
     buttonArray = Array.prototype.slice.call(buttons, 0); 

    // here we use Array.prototype.forEach(), with its 
    // anonymous function: 
    buttonArray.forEach(function(button) { 
    // 'button' again refers to the current 
    // element of the array of elements over 
    // which we're iterating. 

    // here we add the 'hidden' class-name to 
    // each element of the array over which 
    // we're iterating: 
    button.classList.add('hidden'); 
    }); 
}; 

参考文献:

+0

これは非常に役に立ちました、ありがとうございます – Joe

関連する問題