【问题标题】:remove select, from cloned element [duplicate]从克隆元素中删除选择[重复]
【发布时间】:2011-12-21 00:35:58
【问题描述】:

我有这个 js 代码来添加(克隆)和删除一个元素。

$('#btnAdd1').click(function (event) {
    var num = $('.linguas').length;
    var newNum = new Number(num + 1);

    var newElem = $('#input_' + num).clone(false).prop('id', 'input_' + newNum);

    newElem.children(':text').val('');

    $('#input_' + num).after(newElem).find('#input_' + num +'> option:selected').removeAttr("selected");
    $('#btnDel1').prop('disabled', '');
    if (newNum == 4) $('#btnAdd1').prop('disabled', 'disabled');
});

但是,我想删除从前一个元素克隆的 select="select" 属性。

我正在尝试这样的事情,但没有奏效:

 $('#input_' + num).after(newElem).find('#input_' + num +'> option:selected').removeAttr("selected");

演示here

谢谢

【问题讨论】:

    标签: javascript jquery clone


    【解决方案1】:

    单独尝试一下:

    $('option:selected', newElem).prop("selected", false);
    

    您的代码:

    $('#input_' + num).after(newElem).find('#input_' + num +'> option:selected').removeAttr("selected");
    

    将克隆的选择放在原始选择之后,然后您在原始选择上使用find 搜索选定的选项。 find 搜索儿童。克隆的 select 现在是原始的兄弟姐妹,而不是孩子。

    【讨论】:

    • @Daniel 如果您使用的是 jQuery >= 1.6 版本,请使用 .removeProp() 而不是 .removeAttr()
    • @JesseB - 你确定吗?这是来自 removeProp 文档Note: Do not use this method to remove native properties such as checked, disabled, or selected. This will remove the property completely and, once removed, cannot be added again to element. Use .prop() to set these properties to false instead.
    • @JesseB:你肯定不想那样做。 See the docs 原因。相反,你应该做.prop('selected',false)。 ...呃,就像亚当上面说的那样。 :)
    • @ЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖΞЖ - 谢谢你的评论 - +1 - 我确实在那里学到了一些东西,并更新了我的答案:)
    • @AdamRackis 哎呀,我的错。你们是对的;p
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-27
    • 1970-01-01
    • 1970-01-01
    • 2014-03-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多