In the dom event, a for statement is allowed, but not a for in statement. Why is this happening?

Asked 2 years ago, Updated 2 years ago, 125 views

React creates a check box for selecting and releasing all of them, and makes the detailed check box follow the entire check box. It can't be a for in statement, but it can be a for statement. Why is this happening?

import React, {Component} from 'react'
import axios from 'axios'

class SETTING extends Component{

    componentDidMount(){
        axios.get('/setting')
        .then((res)=>{
            for(var i in res.data.results){

                var check = document.createElement('input')
                check.setAttribute('type', 'checkbox')
                check.setAttribute('class', 'check')
                check.setAttribute('value', res.data.results[i].num)
                check.setAttribute('name', res.data.results[i].name)

                var li = document.createElement('li')
                var text = document.createTextNode(res.data.results[i].name)
                li.appendChild(check)
                li.appendChild(text)

                var ul = document.querySelector('#list')
                ul.appendChild(li)
            }
        })
    }

    render(){
        return(
            <div>
                <ul></ul>

                <input type='checkbox' id='allcheck' onClick={()=>{
                    var allCheck = document.querySelector('#allcheck')
                    var checkArr = document.querySelectorAll('.check')


                    for(var i=0; i<checkArr.length; i++){
                        checkArr[i].checked=allCheck.checked
                    }
                    // // for(var i in checkArr){
                    //  //  checkArr[i].checked=allCheck.checked
                    // } //I don't know why this part doesn't work.
                }}>
                </input>

                <ul id='list'></ul>

            </div>
        )
    }
}

html javascript react

2022-09-21 10:44

3 Answers

https://codepen.io/noritersand/pen/GRJrqgp?editors=1111

It's working well


2022-09-21 10:44

It's been a while since I've used JavaScript. The general for statement refers to the list as an index of checkArr, and for in means each element.

for(var item in checkArr){
    item.checked=allCheck.checked
}

Wouldn't it be in the form?


2022-09-21 10:44

If you don't consider IE browsers, there's this way:

let cka = document.querySelector('#cka');
cka.addEventListener('change', (event) => {
  let nodes = document.querySelectorAll('[data-cm]');
  for(var entry of nodes.entries()) { 
    entry[1].checked = event.target.checked;
  }
}); 

https://developer.mozilla.org/ko/docs/Web/API/NodeList/entries


2022-09-21 10:44

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.