自定义属性值 Javascript
内联样式属性的值例如 style = "color: green; background: red;"
。如果我只想动态更改使用 Javascript 属性样式更改的背景,我可以这样做:
element.style.background = "blue"
如何创建“自定义”属性,以便属性中的值可以动态更改?
例如:
myAttributes = "car: mercedes; truck: volvo;"
这样我就可以随着样式的变化而动态地更改汽车值,作为
element.myAttributes.car = "ferrari"
或 是否
setAttributes ("myAttributes", car = "ferrari" )
有可能做到这一点,或者一些类似的替代方案,一些想法?
var get_att = document.getElementById("demo").getAttribute("vehicles");
// how to get vehicles attributes and convert to object?
const vehicles = {car:"mercedes", truck:"volvo"};
// const vehicles = get_att;
// how to add the get_att variable here?
vehicles.car = "ferrari";
const setVehicles = (Object.entries(vehicles).map(([k, v]) => `${k}: ${v}`).join("; "));
console.log(setVehicles);
document.getElementById("demo").setAttribute("vehicles", setVehicles);
<div id="demo" vehicles="car: mercedes; truck: volvo"></div>
The inline style attributes has values such as style = "color: green; background: red;"
. If I want to dynamically change only the background I change with the Javascript attribute style, I do it with:
element.style.background = "blue"
How to create a "custom" attribute so that the values within an attribute can change dynamically?
For example:
myAttributes = "car: mercedes; truck: volvo;"
so that I change only car values dynamically as style changes, as an
element.myAttributes.car = "ferrari"
or with
setAttributes ("myAttributes", car = "ferrari" )
Is there a possibility to do this, or some similar alternative, some idea?
var get_att = document.getElementById("demo").getAttribute("vehicles");
// how to get vehicles attributes and convert to object?
const vehicles = {car:"mercedes", truck:"volvo"};
// const vehicles = get_att;
// how to add the get_att variable here?
vehicles.car = "ferrari";
const setVehicles = (Object.entries(vehicles).map(([k, v]) => `${k}: ${v}`).join("; "));
console.log(setVehicles);
document.getElementById("demo").setAttribute("vehicles", setVehicles);
<div id="demo" vehicles="car: mercedes; truck: volvo"></div>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
数据集
为此目的。这是一个小演示:更接近您的格式的解决方案
虽然这不是最佳实践(由于此格式中允许的字符的限制),但以下是一些辅助函数,可用于获取和设置您要使用的属性语法中的各个属性:
You can use
dataset
for that purpose. Here is a small demo:Solution more close to your format
Although this is not best practice (due to the limitations on the allowed characters in this format), here are some helper functions to get and set individual properties in the attribute syntax you want to use:
HTML 属性必须是字符串值,您无法像对象一样解析它。对于解析属性,您可以使用 JSON.stringify() 和 JSON.parse() 来设置属性值。
例子:
设置:
并解析
HTML Attributes must be a string value you can't parse this like a object. For parse attributes you can you JSON.stringify() and JSON.parse() for setting you attribute values.
Example:
setting:
and parse