jQuery: rename duplicate id
I would like t开发者_开发知识库o insert multible sliders in one page. I have a block of code I would like to reuse but it will insert 2 DIV's with id=slider
...
Is it possible to find second element with id=slider
and rename to id=slider01
?
BR. Anders
Try
$('div[id="slider"]:eq(1)').attr("id", "slider01");
http://jsfiddle.net/rYyA7/ - Tested in IE6/8, Firefox, Safari, Chrome and Opera.
You'd be best off doing this by assiging a new id
before you append the second slider to the page. You haven't shown the code for how you're doing that so it's hard to advise on how to do that, but it would be best.
It's possible to find the second slider afterward, when your document is temporarily invalid, but it may be awkward. Again it depends on your code. If you already have a reference to a jQuery object containing the second slider, as a by-product of how you're creating it, it's easy (just use yourvar[1].id = newavlue
). If not, you may be best off searching on the basis of other things the sliders have in common, like say if they're both div
s with the class slider
:
var sliders, ids;
sliders = $("div.slider");
if (sliders.length > 1) {
ids = {};
sliders.each(function() {
if (ids["x" + this.id]) {
// This ID has already been used, grab a new one
this.id = 'newslider' + new Date().getTime();
}
else {
// This ID hasn't been used yet; flag that we're using it
ids["x" + this.id] = true;
}
});
}
That code walks through all of the matching elements and ensures that there are no duplicate IDs (with a couple of caveats, mainly that there aren't already IDs in the form "newsliderNNNNNNNNNN" where the Ns are the number returned by new Date().getTime()
). (The "x" prefix on the property names in the ids
object is just to defend against accidental collisions with pre-existing properties, like toString
. Hey, it's a valid id
, someone might use it. :-) )
Andy E's head's answer provides a much shorter way of doing it and may be a way to go, but it assumes that searching on the basis of the id
attribute won't get optimized at some stage such that it stops finding multiple elements. That assumption may well be valid, but I'd be uncomfortable relying on the selector implementation not changing down-the-line and introducing an issue in my code. (There's been a lot of work on selectors the last few years; the current jQuery engine, Sizzle, is brand-new for instance.) But again, it may be fine.
i would do it like that:
$('div[id="slider"]').not(':eq(0)').each(function(i){ //selects all divs with the id slider but not the first one
var $that = $(this),
newID = $that.attr('id') + (i + 1) // adds a incising number to the ID's
$that.attr('id', newID) // sets the new id
})
check the example here: http://jsfiddle.net/nuW34/
精彩评论