简体   繁体   English

数组值在 DOM 中没有变化,但在 console.log 中显示正确

[英]array values do not change in DOM, but shows correct in in console.log

I have an array of numbers that goes into a DOM-list.我有一个进入 DOM 列表的数字数组。

When I modify the array values with some array method, I'm not able to render it in the browser.BUT shows correctly in console.log or alert.当我使用某种数组方法修改数组值时,我无法在浏览器中呈现它。但在 console.log 或警报中正确显示。

https://jsfiddle.net/0h672ruz/10/ https://jsfiddle.net/0h672ruz/10/

<form action="">
        <input type="radio" name="radio" id="radioBtn1" class="radio">
        <input type="radio" name="radio" id="radioBtn2" class="radio">
    </form>
<ul>
    <li></li>
    <li></li>
    <li></li>
</ul>
let radioBtns = document.querySelectorAll(".radio");
let lists = document.querySelectorAll("li");

let numsArr = [11, 22, 33]; 

    for (let j = 0; j < radioBtns.length; j++) {
    radioBtns[j].addEventListener('click', function(){
      if(radioBtns[0].checked){
        changeArr();
        alert(numsArr);
        } 
  })

}

//modify numsArr
function changeArr(){
numsArr.splice(0, 1, 44)
}

for (let i = 0; i < lists.length; i++) {
    lists[i].innerHTML = numsArr[i]; 
}
```

You are not updating the DOM as part of the callback.作为回调的一部分,您不会更新 DOM。

Move this inside your callback:将其移动到您的回调中:

for (let i = 0; i < lists.length; i++) {
    lists[i].innerHTML = numsArr[i]; 
}

You should end up with something like this你应该最终得到这样的东西

radioBtns[j].addEventListener('click', function(){
 if(radioBtns[0].checked){
   changeArr();
   for (let i = 0; i < lists.length; i++) {
    lists[i].innerHTML = numsArr[i]; 
   }
   alert(numsArr);
 } 
})

It would be even better to move that code inside a function and call it.将代码移动到 function 中并调用它会更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM