问题
I have an element that contains an attribute called "sound". The value of this sound attribute is an object. One of the properties in this object is "volume".
In other words:
<a-entity position='0 0 0' sound='src: url; on: click; volume: 2.0;'></a-entity>
So it's like this:
{
position: '0 0 0',
sound: {
src: 'url',
on: 'click',
volume: '2.0'
}
}
I'm using setAttribute to update the volume attribute but I don't know if there's an effective way to only target one property while not changing the other properties in the object.
Basically this replaces the sound object and removes all the properties that are not specified (src AND on properties are removed):
element.setAttribute('sound', {
volume: '4'
});
I don't want to replace the entire object. I only want to replace one value for one property. Is there a best way to go about this?
回答1:
You can make use of the 3-argument version of setAttribute which is in the docs here: https://aframe.io/docs/core/entity.html#Updating-Multi-Property-Component-Data
Specifically you can do something like:
element.setAttribute("sound", "volume", "4");
回答2:
You could get object corresponding to the attribute, and replace only the properties you need.
Something like this:
var data = element.getAttribute('sound');
data.volume = '4';
element.setAttribute('sound', data);
Edit
If you set the data in the html like a real JS object, you could do:
var newData = JSON.parse(element.getAttribute('sound'));
newData.volume = 4;
element.setAttribute('sound', JSON.stringify(newData));
Here is a fiddle
来源:https://stackoverflow.com/questions/36568225/how-do-i-update-one-value-within-an-object-using-setattribute