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

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

    You can set the id attribute to a computed value. There is a function in the prototype library that can do this for you.

    http://www.prototypejs.org/api/element/identify

    My favorite javascript library is jQuery. Unfortunately jQuery does not have a function like identify. However, you can still set the id attribute to a value that you generate on your own.

    http://docs.jquery.com/Attributes/attr#keyfn

    Here is a partial snippet from jQuery docs that sets id for divs based on the position in the page:

      $(document).ready(function(){
    
        $("div").attr("id", function (arr) {
              return "div-id" + arr;
            });
      });
    

提交回复
热议问题