How to add class to buttons on click

非 Y 不嫁゛ 提交于 2021-02-11 04:27:39

问题


Sorry for silly question , but I can't add class to button on click. I have list of buttons and on click I need to change background of active button . I dont know how to get index of element on click inside list and add class. I need to make it on pure javascript. Only need to leave $(document).ready(function() . Here is my fiddle 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')
  }) 
});

回答1:


Only need to leave $(document).ready(function()

I am not sure why do you need to leave that when you have the equivalent JavaScript (DOMContentLoaded).

Loop through all the buttons, inside the event handler function first remove the class from all the buttons then add the class only to the clicked button:

document.addEventListener('DOMContentLoaded', () => {

    let myBtns=document.querySelectorAll('.content-itinerary__buttons');
    myBtns.forEach(function(btn) {

        btn.addEventListener('click', () => {
          myBtns.forEach(b => b.classList.remove('active'));
          btn.classList.add('active');
        });
 
    });

});
.active {
    color: #fff;
    background-color: #4CAF50;
}
<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>



回答2:


You just need to use event object in click event

$(document).ready(function() {
  let myBtns=document.querySelectorAll('.content-itinerary__buttons-wrapper')[0];

  myBtns.addEventListener('click', (e)=> {
    if (e.target.className.indexOf('clicked') === -1) {
      e.target.className += ' clicked';
    } else {
      e.target.className = e.target.className.replace(' clicked', '');
    }
  })
});



回答3:


This is your solution

var header = document.getElementById("myDIV");
var btns = header.getElementsByClassName("content-itinerary__buttons");
for (var i = 0; i < btns.length; i++) {
  btns[i].addEventListener("click", function() {
  var current = document.getElementsByClassName("active");
  current[0].className = current[0].className.replace(" active", "");
  this.className += " active";
  });
}
.content-itinerary__buttons-wrapper {
    display: flex;
    margin-top: 20px;
}

.content-itinerary__buttons {
    flex-grow: 1;
    padding: 21px 15px 15px 15px;
    box-sizing: border-box;
    border: 1px solid #D7D7D7;
    outline: none;

    &:not(:last-child) {
        border-right: 0;
    }

}

.active, .btn:hover {
  background-color: red;
  color: white;
}
<div class="content-itinerary__buttons-wrapper" id="myDIV">
     <button  class="content-itinerary__buttons description-text active ">Day 2</button>
     <button class="content-itinerary__buttons description-text">Day 3</button>
     <button class="content-itinerary__buttons description-text ">Day 4</button>
     <button class="content-itinerary__buttons description-text">Day 5</button>
     <button class="content-itinerary__buttons description-text">Day 6</button>
     <button class="content-itinerary__buttons description-text">Day 7</button>
     <button class="content-itinerary__buttons description-text">Day 8</button>
     <button class="content-itinerary__buttons description-text">Day 9</button>
     <button class="content-itinerary__buttons description-text">Day 10</button>
</div>

See Code link




回答4:


Onclick of the button you can set class name to the button

function a(e)
{
e.setAttribute("class","active");
}
.active
{
color:red
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content-itinerary__buttons-wrapper">
    <button class="content-itinerary__buttons description-text" onclick="a(this)">Day </button>
    <button class="content-itinerary__buttons description-text" onclick="a(this)">Day </button>
    <button class="content-itinerary__buttons description-text" onclick="a(this)">Day </button>
 </div>



回答5:


If you going to get rid of jQuery replace wrapper function to use listen for DOMContentLoaded event. It's the same as jQuery documentReady.

In your click handler use event object, ev.target in my example is a button which fired the event. Then use classList property to add your class.

document.addEventListener('DOMContentLoaded', function(){
let myBtns=document.querySelector('.content-itinerary__buttons-wrapper')

  myBtns.addEventListener('click', (ev)=>{
    let btn = ev.target;
    btn.classList.add('red');
  });
});



回答6:


I would definitely use Element.classList API for adding/removing classes to/from elements.

Why?

  • Adding/removing classes won't affect other classes already set to the element
  • Updating the className of the element will replace all existing classes
  • It comes with handy functions like "toggle" and "replace

Your code will look something like this:

$(document).ready(function() {
let myBtns=document.querySelectorAll('.content-itinerary__buttons-wrapper')

  myBtns
    .forEach(btn => btn
        .addEventListener('click', (e)=>{
        // Check if the classList already exists on the element clicked
        // If so, remove it
        // Else, add it
            e.classList.contains('clicked') 
                ? e.classList.add('clicked') 
                : e.classList.remove('clicked');
        })
    ); 
});



回答7:


Just use forEach loop :)

$(document).ready(function() {
 let myBtns=document.querySelectorAll('.content-itinerary__buttons-wrapper')

 let myAllButtons = myBtns.querySelectorAll('.content-itinerary__buttons')

 myAllButtons.forEach(function(element) {
    element.onclick = () => element.classList.add('some-class')
 })
});


来源:https://stackoverflow.com/questions/57143671/how-to-add-class-to-buttons-on-click

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!