我有以下表格
<div id="div1" style="margin-bottom:4px;" class="clon">
<span id ="display_input1">
Answer:<select name="Answer1" id="Answer1">
<option value='0'>Select Answer</option>
<option value='1'>Excellent</option>
option value='2'>Very Good</option>
</select>
</span>
New Answer<input type="checkbox" id="Enable1" name="Enable1" value="1" onclick=display_inpt(this) />
<?
function dropdown($starting, $factor, $ending)
{
echo "Point<select name=\"Mark1\" id=\"Mark1\">";
echo "<option value=\"\">Select Point</option>";
$i=$starting;
while($i >= $ending)
{
echo "<option value=\"$i\">$i</option>";
$i=$i-$factor;
}
echo "</select>";
}
dropdown(10, .5, -10);
?>
</div>
<input type="button" id="Add" value="Add Another Option" />
我想在每次点击“添加另一个选项”按钮时克隆整个div,这样rasult就像
<div id="div2" style="margin-bottom:4px;" class="clon">
<span id ="display_input2">
Answer:<select name="Answer2" id="Answer2">
等等。我尝试使用以下jquery代码来实现此目的
$(document).ready(function() {
$('#Add').click(function() {
var num = $('.clon').length;
var newNum = new Number(num + 1);
var newElem = $('#div' + num).clone().attr('id', 'div' + newNum);
newElem.children(':eq(0)').attr('id', 'display_input' + newNum);
newElem.children(':eq(1)').attr('id', 'Answer' + newNum).attr('name', 'Answer' + newNum);
newElem.children(':eq(2)').attr('id', 'Enable' + newNum).attr('name', 'Enable' + newNum).attr('value', newNum);
newElem.children(':eq(3)').attr('id', 'Mark' + newNum).attr('name', 'Mark' + newNum);
但这不正确,那么我应该如何编写jquery代码来实现呢?
答案 0 :(得分:0)
检查这个小提琴:http://jsfiddle.net/techfoobar/JwwkT/
id和名称重命名的基础是通过以下方式完成的:
function doClone() {
var old = $('.clon').length;
var newC = old + 1;
var cloned = $('.clon:first').clone();
// add more element types as needed here
cloned.find('p,input,select').each(function() {
id = $(this).attr('id');
name = $(this).attr('name')
$(this).attr('id', id.substring(0, id.length-1) + newC).attr('name', name.substring(0, name.length-1) + newC);
});
// change the parent container as needed
cloned.appendTo('body');
}
可能的增强是将选择器,新索引和父容器作为上述函数的参数传递。例如:
doClone('.clon:first', $('.clon').length+1, 'body');
答案 1 :(得分:0)
以下jsfiddle示例可以执行您想要的操作:http://jsfiddle.net/nLJTP/
我写了一个简短的代码片段,它增加了所有元素的id和名称,其中包含“increaseNumbers”类:
$(clonedElement).find('.increaseNumbers').each(function(){
var oldId = $(this).attr('id');
var oldName = $(this).attr('name');
var regexp = new RegExp(/(.*?)(\d.*)/);
if (oldId) {
var matcher = oldId.match(regexp);
var newId = matcher[1] + (parseInt(matcher[2]) + 1);
$(this).attr('id', newId);
}
if (oldName) {
var matcher = oldName.match(regexp);
var newName = matcher[1] + (parseInt(matcher[2]) + 1);
$(this).attr('name', newName);
}
});