jquery创建一个唯一的id

Udd*_*ers 12 javascript jquery

$(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;
  });
});
Run Code Online (Sandbox Code Playgroud)

正如您所看到的,我正在创建一个div并向其中添加一些内容,我将如何为每个div创建一个唯一ID,如section1,section2,section3等?

cle*_*tus 24

只需使用一个柜台:

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

另外,我建议按上述方法创建元素.


mar*_*r10 17

从jQuery 1.9 UI开始,有一个$().uniqueId()函数,它设置一个唯一的id属性(如果没有定义id):

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

(注意,这需要在jQuery之上使用jQueryUI.)