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

前端 未结 13 1232
抹茶落季
抹茶落季 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:13

    UPDATE: Closures are indeed the answer. So after fiddling with it some more, I figured out why closures were initially problematic and how to fix it. The tricky thing with a closure is you have to be careful when iterating through the elements not to end up with all of your closures referencing the same element. For example, this doesn't work:

    for (var i = 0; i < elements.length; i++) {
        var element = elements[i];
        var button = document.createElement("button");
        button.addEventListener("click", function(ev) {
            // do something with element here
        }, false)
    }
    

    But this does:

    var buildListener = function(element) {
        return function(ev) {
            // do something with event here
        };
    };
    
    for (var i = 0; i < elements.length; i++) {
        var element = elements[i];
        var button = document.createElement("button");
        button.addEventListener("click", buildListener(element), false)
    }
    

    Anyway, I decided not to select one answer because the question had two answers: 1) No, there are no internal IDs you can use; 2) you should use closures for this. So I simply upvoted the first people to say whether there were internal IDs or who recommended generating IDs, plus anyone who mentioned closures. Thanks for the help!

提交回复
热议问题