问题
$(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