自定义属性值 Javascript

发布于 2025-01-12 16:55:41 字数 1223 浏览 0 评论 0原文

内联样式属性的值例如 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

时光瘦了 2025-01-19 16:55:41

您可以使用数据集 为此目的。这是一个小演示:

let div = document.querySelector("div");

Object.assign(div.dataset, { water: "Morshinska", juice: "Sandora" });

console.log(div.dataset.water);

div.dataset.water = "Spa";

console.log(div.dataset.water);

console.log(Object.entries(div.dataset)
                  .map(([k, v]) => `${k}: ${v}`)
                  .join("; "));
<div></div>

更接近您的格式的解决方案

虽然这不是最佳实践(由于此格式中允许的字符的限制),但以下是一些辅助函数,可用于获取和设置您要使用的属性语法中的各个属性:

function getMyAttributes(elem) {
    const regex = /([^:;=]*):([^:;=]*)/g
    return Object.fromEntries(Array.from(elem.dataset.myattr?.matchAll(regex)??[], ([_, k, v]) =>
        [k.trim(), v.trim()]
    ));
}

function setMyAttributes(elem, obj) {
    const regex = /[:;]/g;
    elem.dataset.myattr = Object.entries(obj).map(([k, v]) => {
        if (regex.test(k) || regex.test(v)) throw "Invalid character in key/value pair";
        return `${k}: ${v};`;
    }).join(" ");
}

function setMyAttribute(elem, key, value) {
    setMyAttributes(elem, {...getMyAttributes(elem), ...{[key]: value}});
}

function getMyAttribute(elem, key) {
    return getMyAttributes(elem)[key];
}

// Demo
let div = document.querySelector("div");
console.log(getMyAttribute(div, "water"));
setMyAttribute(div, "water", "Spa");
console.log(getMyAttribute(div, "water"));
console.log(div.dataset.myattr);
<div data-myattr="water: Morshinska; juice: Sandora;"></div>

You can use dataset for that purpose. Here is a small demo:

let div = document.querySelector("div");

Object.assign(div.dataset, { water: "Morshinska", juice: "Sandora" });

console.log(div.dataset.water);

div.dataset.water = "Spa";

console.log(div.dataset.water);

console.log(Object.entries(div.dataset)
                  .map(([k, v]) => `${k}: ${v}`)
                  .join("; "));
<div></div>

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:

function getMyAttributes(elem) {
    const regex = /([^:;=]*):([^:;=]*)/g
    return Object.fromEntries(Array.from(elem.dataset.myattr?.matchAll(regex)??[], ([_, k, v]) =>
        [k.trim(), v.trim()]
    ));
}

function setMyAttributes(elem, obj) {
    const regex = /[:;]/g;
    elem.dataset.myattr = Object.entries(obj).map(([k, v]) => {
        if (regex.test(k) || regex.test(v)) throw "Invalid character in key/value pair";
        return `${k}: ${v};`;
    }).join(" ");
}

function setMyAttribute(elem, key, value) {
    setMyAttributes(elem, {...getMyAttributes(elem), ...{[key]: value}});
}

function getMyAttribute(elem, key) {
    return getMyAttributes(elem)[key];
}

// Demo
let div = document.querySelector("div");
console.log(getMyAttribute(div, "water"));
setMyAttribute(div, "water", "Spa");
console.log(getMyAttribute(div, "water"));
console.log(div.dataset.myattr);
<div data-myattr="water: Morshinska; juice: Sandora;"></div>

澉约 2025-01-19 16:55:41

HTML 属性必须是字符串值,您无法像对象一样解析它。对于解析属性,您可以使用 JSON.stringify() 和 JSON.parse() 来设置属性值。

例子:
设置:

const el = document.body 
el.setAttribute("my-attribute", JSON.stringify({car: "bmw", owner: "user1234"}))

并解析

    JSON.parse(document.body.getAttribute('my-attribute'))

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:

const el = document.body 
el.setAttribute("my-attribute", JSON.stringify({car: "bmw", owner: "user1234"}))

and parse

    JSON.parse(document.body.getAttribute('my-attribute'))
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文