【问题标题】:How to clone HTML select tag and change its ID in the process?如何克隆 HTML 选择标签并在此过程中更改其 ID?
【发布时间】:2015-07-03 11:37:13
【问题描述】:

我可以更改除toCity 之外的所有其他字段的 ID。克隆它时如何更改其 ID?使用我当前的代码,下拉菜单是使用相同的数据创建的,但 ID 保持不变。

克隆时如何更改 ID?

var toAddCloneCount = 1;

function AddDestination() {
    var clone = $("#toAdd").clone(true);
    clone.find("#days").prop('id', 'days' + toAddCloneCount);
    clone.find("#toDate").attr('id', 'toDate' + toAddCloneCount);
    clone.find('#toCity').prop('id', 'toCity' + toAddCloneCount);
    clone.show();
    clone.attr('id', 'toAdd' + toAddCloneCount++).insertAfter("#toAdd");
    clone.appendTo("#destinations");
}
<div id="destinations">
    <div id="toAdd">
        <table style="width: 100%;">
            <tr>
                <td class="auto-style8">To </td>
                <td>
                    <select runat="server" id="toCity" name="toCity"></select>
                </td>
                <td>Days to Stay</td>
                <td>
                    <input id="days" type="number" min="1"  onkeypress="return false" onkeydown="return false" />
                </td>
                <td>
                    <p>
                        Date:         
                        <input id="toDate" type="text" class="getCurrentDate"   onkeypress="return false" onkeydown="return false" />
                    </p>
                </td>
                <td>
                    <button type="button" onclick="AddDestination();" >Add+</button>
                </td>
            </tr>
        </table>
    </div>
</div>

【问题讨论】:

  • 也试试改名
  • 我不是 asp 人,但我想这是因为 runat="server" 然后更改了客户端 ID
  • 我想你在同一个问题上得到了答案(由你发布):stackoverflow.com/questions/31202042/…,这里不是代码调试。

标签: javascript jquery asp.net


【解决方案1】:
var source = document.getElementById('id_here');
var options = source.innerHTML;
var copy = document.createElement("Select"); 
copy.id = "copy_id"
copy.innerHTML = copy.innerHTML + options;
document.body.appendChild(copy);

【讨论】:

    【解决方案2】:

    您可以为元素生成新的 ID 和名称:

    $("button").click(function () {
    var num = ($("div[id^='cloneItem_']").length + 1);
    //alert(num);
    $("#cloneItem_1").clone().insertAfter($("div[id^='cloneItem_']").last()).attr("id", 'cloneItem_' + num).find("select").each(function () {
    
        $(this).prop({
            'id': function (_, id) {
                id = id.substring(0, id.indexOf('_') + 1);
                return id + num;
            },
                'name': function (_, name) {
                name = name.substring(0, name.indexOf('_') + 1);
                return name + num;
            },
                'value': ''
        });
    
    });
    

    });

    转到小提琴演示:clone select element

    【讨论】:

    • 下拉列表与数据绑定...仍然 id 保持不变
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多