jquery create a unique id

痴心易碎 提交于 2019-12-17 18:39:45

问题


$(document).ready(function() {
  $('a.menuitem').click(function() {
      var arr = 0;
      var link = $( this ), url = link.attr( "href" );
      var newDiv = $( document.createElement( 'div' ) )
      $( "#content_pane" ).append( newDiv );
      newDiv.load( url );
      return false;
  });
});

As you can see I am creating a div and adding some content to it, how would I give each div that is created a unique id, something like section1, section2, section3, etc?


回答1:


Just use a counter:

var section = 1;
$(function() {
  $("a.menuitem").click(function() {
    ...
    $("<div></div>").attr("id", "section" + section++).appendTo("#content_pane");
    ...
    return false;
  });
});

Also, I'd suggest creating the element as per above.




回答2:


Starting with jQuery 1.9 UI there is a $().uniqueId() function, that sets a unique id attribute (if no id is already defined):

http://api.jqueryui.com/uniqueId/

(Note that this requires jQueryUI on top of jQuery.)




回答3:


You shouldn't need to do this. If you can store the id in a variable, you could store the element itself (well, a reference to the element) in a variable too.




回答4:


Now that Backbone.js has gained popularity, if you include it you automatically have access to Underscore just use: Underscore: uniqueId.

Or include it by itself, it's pretty lightweight and has some great functions



来源:https://stackoverflow.com/questions/1817114/jquery-create-a-unique-id

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!