繁体   English   中英

数组中的元素自动更新

[英]Element in array updates automatically

我有一个普通的数组,这个数组的每个元素都是一个HTML元素。 当我将HTML元素添加到数组并稍后更改该元素(更改其类或....)时,我的数组也会自动更新,但我不希望这样,我希望我的数组保持旧的html元素状态。

 let btn = document.querySelector('.btn') ; let arr = [] ; btn.addEventListener('click',function(e){ arr.push(this) ; //now 'arr' is [button.btn] console.log(arr) ; //[button.btn] this.classList.add('something') ; //this line will also update 'arr' too but I dont want this and I //want arr still holds [button.btn] console.log(arr) ; //[button.btn.something] }) 
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css"> <link rel="stylesheet" href="css/style.css"> </head> <body> <button class="btn">click me</button> </body> </html> 

发生的事情是当你将this附加到你的数组时,你要保存对当前元素的引用,而不是当前元素的副本。 因此,当元素发生更改时,对该元素的所有引用都将反映这些更改。

为了解决这个问题,你应该在将它附加到数组之前创建一个副本,这样你就可以创建元素状态的“快照”并保存它,这样以后对元素的任何未来更改都不会反映出来。列表中元素的副本。

重要的变化是行: arr.push(this.cloneNode(true)); 而不只是附加this我通过调用this.cloneNode(true)创建一个副本。

 let btn = document.querySelector('.btn') ; let arr = [] ; btn.addEventListener('click',function(e){ arr.push(this.cloneNode(true)) ; //now 'arr' is [button.btn] console.log(arr) ; //[button.btn] this.classList.add('something') ; //this line will also update 'arr' too but I dont want this and I //want arr still holds [button.btn] console.log(arr) ; //[button.btn.something] }) 
 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.9.0/css/all.min.css"> <link rel="stylesheet" href="css/style.css"> </head> <body> <button class="btn">click me</button> </body> </html> 

暂无
暂无

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

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