真的很难达到我想要的效果。我基本上需要创建对象的链接,这些对象将包含对 HTMLElements 的引用。当此对象内的状态值发生更改时,应添加/删除一个类。
但是,当我创建此对象的副本时,我需要保留到此状态的链接,因此所有其他属性都是唯一的,并且在此副本中设置新图像,但是如果状态是要在第一个对象中更改,那么它也应该在这个新对象中更改,但引用新图像。
我有以下脚本示例,但是当第一个对象内的状态发生更改时,第二个对象不会更改。我相信我没有保留对旧对象属性的引用。
<img src="https://mgreviewsblog.files.wordpress.com/2014/08/2014-ducati-899-panigale-white-16.jpg" alt="Image 1" class="responsive-img" data-lightbox-group="detail_gallery" data-lightbox-name="Gallery">
<img src="https://mgreviewsblog.files.wordpress.com/2014/08/2014-ducati-899-panigale-white-1.jpg" alt="Image 2" class="responsive-img" data-lightbox-group="detail_gallery" data-lightbox-name="Gallery">
<img src="https://mgreviewsblog.files.wordpress.com/2014/08/2014-ducati-899-panigale-white-3.jpg" alt="Image 3" class="responsive-img" data-lightbox-group="detail_gallery" data-lightbox-name="Gallery">
<script>
let images = querySelectorAll('img');
images = Array.from(images, function (elm) {
var activeState = {
_state: 0,
object: null,
set State(val) {
if (this._state !== val) {
switch(val) {
case 0:
elm.classList.remove('active');
break;
case 1:
this.object.classList.add('active'); // Needs to reference image within object
break;
}
this._state = val;
};
}
};
return {
object: elm, // Store a reference to the image
_active: activeState,
get activeState() {
this._active.object = this.object;
return this._active;
}
};
});
// Duplicate the above object, but retain the state object,
// however the object within the state needs to be different.
let clone = [];
for (let i = 0; i < _.images.length; i++) {
var img = document.createElement('img');
img.src = _.images[i].object.src;
img.alt = _.images[i].alt;
newList.push({
object: img,
index: i,
src: _.images[i].src,
alt: _.images[i].alt,
_active: _.images[i].activeState, // Retain reference to active state across objects
get activeState() {
this._active.object = this.object;
return this._active;
}
});
}
</script>
编辑 简化版:
var test = {
object: 'test1',
_active: { val: 0 },
active: function(x) {
this._active.val = x;
console.log(this._active);
}
};
var test2 = {
object: 'test1',
_active: test._value,
active: test.value
};
_active.val
保持跨对象的链接,但是如果我像这样 test2.active(2)
更改它,则只有 test2 值是执行后,测试也应该执行。
最佳答案
我认为你的整个代码过于复杂。我会这样做:
function statify(el,state){
var obj={
get state(){
return state;
},
set state(v){
state=v;
if(v){
el.classList.add("active");
}else{
el.classList.remove("active");
}
},
get el(){return el;},
cloneTo(el){
return statify(el,state);
}
};
obj.state=state;
return obj;
}
所以你可以像这样使用它:
var states=Array.from(images).map(image=>statify(image));
states[0].state=1;
var clone=states.map(function(state){
var el=state.el;
var img=document.createElement("img");
img.src=el.src;
return state.cloneTo(img);
});
关于javascript - 复制对象,保留一个属性链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45030145/