使用 DOM 对象创建备份数组
我有
现在,用户更改 元素中的一些
option
一个。在对
但无论如何,选项上的更改似乎适用于两个数组。
我使用 new Array
创建了备份数组,并将每个选项
推送到新数组中。我希望这可以防止它们在从 DOM 中删除时也从数组中删除。
有任何提示我如何解决这个问题吗?
function cacheOptions() {
backupOptions = newArray(document.getElementById("selectElement").options);
}
function newArray(oldArray) {
var newArray = new Array(oldArray.length);
for ( var object in oldArray) {
newArray.push(object);
}
return newArray;
}
并删除 onchange
方法中的 option
...
document.getElementById("selectElement").options[i].remove();
I've got <select>
element a with different option
s. When loading the page, I want to store these option
s as a backup (I'm doing this with window.onload
).
Now the user changes <select>
element b, which removes some option
s in <select>
element a. After some other change on <select>
element b, I want to restore the option
s of element a with my backup from the startup.
But no matter what, the changes on the option
s seem to apply to both arrays.
I've created the backup arrray with new Array
and push
ed each of the option
s into the new array. I hoped that this would prevent them from being removed from the array when they're removed from the DOM.
Any hints how I can solve this problem?
function cacheOptions() {
backupOptions = newArray(document.getElementById("selectElement").options);
}
function newArray(oldArray) {
var newArray = new Array(oldArray.length);
for ( var object in oldArray) {
newArray.push(object);
}
return newArray;
}
And removing the option
s in an onchange
method …
document.getElementById("selectElement").options[i].remove();
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
for in
循环数组;使用普通的for
循环arr = []
创建一个数组;长度将自动设置无论如何,您可以使用
[].slice.call(arr)
从类似数组的对象获取数组。因此,您最好摆脱
newArray
函数,并将cacheOptions
函数更改为:for in
to loop over an array; use a normalfor
looparr = []
; the length will be set automaticallyAnyhow, you can just use
[].slice.call(arr)
to get an array from an array-like object.So, you'd best get rid of the
newArray
function, and change thecacheOptions
function to: