很抱歉提出愚蠢的问题,但我无法在单击时将类添加到按钮。我有按钮列表,单击时我需要更改活动按钮的背景。我不知道如何在列表中单击并添加类时获取元素索引。我需要在纯 javascript 上制作它。只需要离开 $(document).ready(function()
。这是我的小提琴 https://jsfiddle.net/armakarma/ns5tfcL0/15/
HTML
<div class="content-itinerary__buttons-wrapper">
<button class="content-itinerary__buttons description-text ">Day 2</button>
<button class="content-itinerary__buttons description-text">Day 3</button>
<button class="content-itinerary__buttons description-text">Day 4</button>
</div>
JS
$(document).ready(function() {
let myBtns=document.querySelector('.content-itinerary__buttons-wrapper')
myBtns.addEventListener('click', ()=>{
console.log('test')
})
});
原文由 Yerlan Yeszhanov 发布,翻译遵循 CC BY-SA 4.0 许可协议
只需要离开
$(document).ready(function()
我不确定当您拥有等效的 JavaScript (
DOMContentLoaded
) 时为什么需要保留它。遍历所有按钮,在事件处理函数中首先从所有按钮中删除 _类_,然后仅将 类 添加到单击的按钮: