动态为每个元素创建新的唯一ID [英] Create new unique ids for each element dynamically
问题描述
在下面的代码中,我正在做各种各样的事情,但是现在我看到的是,我为每个菜单项href分配的名称与我要创建的每个元素的ID名称相同.
In the following code, I am doing various things but what I am now looking at is that fact that I am assigning to each menu item href the same name as per the id name of each element I am creating.
$(".nav li a").on("click", function(e) {
$(this).attr("href",$(".span6").attr("id"));
$('#content').removeAttr('id');
var $row = $(".span9");
var $rowNew = $('.new');
if ($rowNew.children().length > 1) {
$(".span9 div").removeClass("new");
$('<div class="row-fluid new"></div>').prependTo($row);
}
if ($(".new").length == 0) {
$('<div class="row-fluid new"></div>').prependTo($row);
$('<div id="content" class="span6"></div>').appendTo('.new');
} else {
$('<div id="content" class="span6"></div>').appendTo('.new');
}
});
这是我为每个菜单项href分配与我要创建的每个元素的ID名称相同的名称的方法:
This is how I am assigning to each menu item href the same name as per the id name of each element I am creating:
$(this).attr("href",$(".span6").attr("id"));
我现在需要为每个<div id="content" class="span6"></div>
我知道它已经有一个名为#content
的ID,但是我想通过点击$('#content').removeAttr('id');
I know it has already an id called #content
but I am removing that on a click using $('#content').removeAttr('id');
如何每次生成新的唯一ID?
How do I generate new unique ids each time?
在另一个使用php的模板中,我这样做:<?php $a = 1; ?>
然后在循环中<div class="span6" id="<?php echo "i".$a; ?>">
然后在<?php $a++; ?>
中,但是在我的情况下使用jquery?
In another template using php i do: <?php $a = 1; ?>
then <div class="span6" id="<?php echo "i".$a; ?>">
in a loop then <?php $a++; ?>
but about in my case with jquery?
我还认为我需要对第一个和最后一个<div id="content" class="span6"></div>
做一些事情,因为它们已经设置了ID #content设置,这些ID仅在下次单击时才被删除,因此创建一个新ID我猜第一个和最后一个会有2个ID.
Also I think I will need to do something in regards of the first and last <div id="content" class="span6"></div>
as these will already have an id #content set, these ids are removed on the next click only at the moment so creating a new id will lead to have 2 ids for the first and last i guess.
推荐答案
您可以使用函数来测试第一个可用的ID.
You can use a function to test the first ID available.
function setId(elem)
{
var first = 0;
while($('#i'+first).length > 0) first++;
elem.setAttr('id', 'i'+first);
}
//Usage:
setId(myJqueryObject);
这篇关于动态为每个元素创建新的唯一ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!