配列全体を反復処理する必要がある方法にかかわらず、すべての配列要素に一度にクラスを追加することはできません。幸いにも、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');
});
};
参考文献:
私はquerySelectorを使用しているので、この特定のケースではjqueryを使用していません – Joe
jqueryを使用していると思われるので、 "jquery-selector"というタグを追加しました。 – ElChupacabra