Unique element ID, even if element doesn't have one

前端 未结 13 1252
抹茶落季
抹茶落季 2020-12-14 00:43

I\'m writing a GreaseMonkey script where I\'m iterating through a bunch of elements. For each element, I need a string ID that I can use to reference that element later. The

13条回答
  •  一个人的身影
    2020-12-14 01:11

    A bit confused by the wording of your question - you say that you "need a string ID that [you] can use to reference that element later, " but that you "can't store the references in [your] script because when [you] need them, the GreaseMonkey script itself will have gone out of scope."

    If the script will have gone out of scope, then how are you referencing them later?!

    I am going to ignore the fact that I am confused by what you are getting at and tell you that I write Greasemonkey scripts quite often and can modify the DOM elements I access to give them an ID property. This is code you can use to get a pseudo-unique value for temporary use:

    var PseudoGuid = new (function() {
        this.empty = "00000000-0000-0000-0000-000000000000";
        this.GetNew = function() {
            var fourChars = function() {
                return (((1 + Math.random()) * 0x10000)|0).toString(16).substring(1).toUpperCase();
            }
            return (fourChars() + fourChars() + "-" + fourChars() + "-" + fourChars() + "-" + fourChars() + "-" + fourChars() + fourChars() + fourChars());
        };
    })();
    
    // usage example:
    var tempId = PseudoGuid.GetNew();
    someDomElement.id = tempId;
    

    That works for me, I just tested it in a Greasemonkey script myself.


    UPDATE: Closures are the way to go - personally, as a hard-core JavaScript developer, I don't know how you didn't think of those immediately. :)

    myDomElement; // some DOM element we want later reference to
    
    someOtherDomElement.addEventListener("click", function(e) {
       // because of the closure, here we have a reference to myDomElement
       doSomething(myDomElement);
    }, false);
    

    Now, myDomElement is one of the elements you apparently, from your description, already have around (since you were thinking of adding an ID to it, or whatever).

    Maybe if you post an example of what you are trying to do, it would be easier to help you, assuming this doesn't.

提交回复
热议问题