2010-07-18 57 views
1

克隆元素并自动增加其id的简单任务。克隆元素和autioincrement id的最快方法(jquery)

它可以在1行吗?

+3

的ID与数字开头的技术上是不合法的。 – cletus 2010-07-18 03:09:11

+0

@cletus - 看起来他们允许HTML 5(http://www.w3.org/TR/html5/elements.html#the-id-attribute)。该值必须至少包含一个字符,并且不能包含任何空格。 – 2010-07-18 03:48:51

回答

3

jQuery的

var NewElement=$("#test1").clone(); // Clone the element 
var IDNr=NewElement.attr("id").match(/\d+$/); // Grab the ID number 

NewElement.attr("id",NewElement.attr("id").replace(IDNr,parseInt(IDNr)+1)); // Increment the ID 

HTML

<div id="test1">Test</div> 

Code in action.