0

我在使用 jquery时遇到问题input[type=radio] 。

我需要复制 div 的内容,但保持默认选中无线电对象

$('#copy').click(function() {
    var copy = '<div id="source">';
    copy += $('#source').html();
    copy += '</div>';
    $(this).after(copy);
});

http://jsfiddle.net/R7EFb/

请帮我!

4

2 回答 2

0

您必须为复制的单选按钮集和标签使用不同的名称属性和 ID。

这是一个JSFiddle 示例

var copyCount = 1;

$("#copy").click(function() {
    $("#source").clone().attr("id", "source" + copyCount).appendTo("body");
    // Get original radio elements
    $radio1 = $("#source" + copyCount + " #radio1");
    $radio2 = $("#source" + copyCount + " #radio2");
    $radio3 = $("#source" + copyCount + " #radio3");
    $radio4 = $("#source" + copyCount + " #radio4");

    // Change attributes (name and id)
    $radio1.attr("id", "radio" + (copyCount * 4 + 1)).attr("name", "check" + (copyCount * 2 + 1)).next().attr("for", "radio" + (copyCount * 4 + 1));
    $radio2.attr("id", "radio" + (copyCount * 4 + 2)).attr("name", "check" + (copyCount * 2 + 1)).next().attr("for", "radio" + (copyCount * 4 + 2));
    $radio3.attr("id", "radio" + (copyCount * 4 + 3)).attr("name", "check" + (copyCount * 2 + 2)).next().attr("for", "radio" + (copyCount * 4 + 3));
    $radio4.attr("id", "radio" + (copyCount * 4 + 4)).attr("name", "check" + (copyCount * 2 + 2)).next().attr("for", "radio" + (copyCount * 4 + 4));

    // Restore selected option in original radio set
    if ($radio1.attr("checked") !== undefined) $("#source #radio1").click();
    if ($radio2.attr("checked") !== undefined) $("#source #radio2").click();
    if ($radio3.attr("checked") !== undefined) $("#source #radio3").click();
    if ($radio4.attr("checked") !== undefined) $("#source #radio4").click();

    copyCount++;
});
于 2013-08-19T13:45:34.040 回答
0

您需要在不复制 ID、名称和属性(如果有)的情况下进行克隆。请在此处检查工作小提琴。

请参阅 globalVarCount 是区分这些的变量。这是代码::

var globalVarCount= 0;
$('#copy').click(function() {
    var copy;
    $clone = $("#source").clone();
    $clone.attr("id",$clone.attr("id")+1)
    $clone.children().each(function(){
        $(this).attr("id",$(this).attr("id")+1);
        $(this).attr("name",$(this).attr("name")+1);
        $(this).attr("for",$(this).attr("for")+1);
    });
    $(this).after($clone);
});
于 2013-08-19T14:13:42.953 回答