简体   繁体   中英

save data for an HTML element such that it can be accessed later

Everything I've read says do not save custom properties or attributes to HTML DOM Elements. So I'm trying to figure out how else I should save properties/attributes for an element such that I can access them later.

Originally I was thinking of using the element as the key in a hash but JS converts hash keys to string so that won't work.

Use case:

function do1(element)
{
    var w = element.style.width;
    element.style.width = "200px";

    // i want to save the w variable for this element somewhere/somehow
}

function do2(element)
{
    // i want to be able to get the w variable i saved earlier for the element
}

I thought of using the element 's ID but the element won't always have an ID that I can use and I can't set one because there might be other JS that dynamically sets ID s for elements.

Why not use data attributes ? They're specifically intended for storing extra data on an element.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM