Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

javascript - set JQuery action for each element spread

I have a list of check boxes Object { 0: div.checkbox-toggle, 1: div.checkbox-toggle, 2: div.checkbox-toggle, length: 3, prevObject: {…} } and each element is as <div class="checkbox-toggle">...</div>

in js file

...
var checkbox = $(".checkbox-toggle")

var ch = true
checkbox.change(function(){
  if (ch) {
    ch = false
    checkbox.css("background", "red")
  } else {
    ch = true
    checkbox.css("background", "green")

  }
})

I want to change only the color of checkbox which I clicks on, but now it change color of all checkboxes. I'm wondring how to set action for each checkbox independent. I also tried setting action with forloop, but couldn't get what i wanted.

question from:https://stackoverflow.com/questions/65873927/set-jquery-action-for-each-element-spread

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can toggle the checkbox background on check click using the class toggle function. With the added css style below when the checkbox is clicked it will have green background if checked or red if not.

I wrapped the snippet in an IIFE to avoid any potential namespace corruption.

(vanilla solution though)

Add this inside <head>

<style>
    .checkbox-toggle:not(.isChecked) {
        background: red;
    }
    .checkbox-toggle.isChecked {
        background: green;
    }
</style>

Add this before </body>

<script>
    void function() {
        const checkboxes = document.getElementsByClassName(".checkbox-toggle");
            
        for (const checkbox of checkboxes) {
            void checkbox.classList.add('isChecked');

            checkbox.onclick = check;
        }
        
        function check(e) {
            const currentCheckbox = e.target || e.srcElement;
          
            void currentCheckbox.classList.toggle('isChecked');
        };
    }();
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...