document.getElementsByClassName('big-button')[0,1,2].style.display = "inline-flex";
我正在尝试将该样式应用于与类名匹配的所有/任何元素。我尝试了[0,1,2]
,因为我只有3个实例,但它只针对第三个实例。
这不需要在生产中工作。只是在Chrome中。只是原型。
答案 0 :(得分:7)
将逗号放在方括号内的值之间时,表示您正在调用逗号运算符,该运算符将评估以逗号分隔的列表中的每个项目,然后评估为列表中的最终值。因此,您的代码求值为[2]
,或仅求第三项。通常,如果左侧有类似数组的对象,则需要在以下方括号中提供单个值,例如[0]
或[1]
。 / p>
如果要将样式应用于列表的前三个元素,则必须显式地对其进行迭代。例如,一种可能的实现是:
const buttons = document.querySelectorAll('.big-button');
const firstThreeButtons = Array.prototype.slice.call(buttons, 0, 3);
firstThreeButtons.forEach(button => button.style.display = 'inline-flex');
答案 1 :(得分:1)
有N种方法可以实现它。
function borderRed(className, elementIndexes) {
elementIndexes.forEach(index => {
document.getElementsByClassName(className)[index].style = "border: 1px solid red";
});
}
borderRed('big-button', [0, 2, 4]);
<button class="big-button">1</button>
<button class="big-button">2</button>
<button class="big-button">3</button>
<button class="big-button">4</button>
<button class="big-button">5</button>
<button class="big-button">6</button>
var buttons = document.getElementsByClassName('big-button');
buttons[0].style = 'border: 1px solid red';
buttons[2].style = 'border: 1px solid red';
buttons[4].style = 'border: 1px solid red';
<button class="big-button">1</button>
<button class="big-button">2</button>
<button class="big-button">3</button>
<button class="big-button">4</button>
<button class="big-button">5</button>
<button class="big-button">6</button>
$(function() {
$('.big-button').slice(0, 3).css('border', '1px solid red');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="big-button">1</button>
<button class="big-button">2</button>
<button class="big-button">3</button>
<button class="big-button">4</button>
<button class="big-button">5</button>
<button class="big-button">6</button>
document.querySelector
var buttons = document.querySelectorAll('.big-button:nth-child(1),.big-button:nth-child(3),.big-button:nth-child(5)');
buttons.forEach(button => button.style = 'border: 1px solid red');
<button class="big-button">1</button>
<button class="big-button">2</button>
<button class="big-button">3</button>
<button class="big-button">4</button>
<button class="big-button">5</button>
<button class="big-button">6</button>