javascript - 如何使用 jQuery 重置克隆对象的值?

标签 javascript jquery

我正在尝试在我的 DOM 中查找并克隆一个元素。克隆后,我想清除元素值,然后将它们附加到容器底部。

出于某种原因,我似乎无法清除该值。目前,该行被附加但具有与第一行相同的值。我想克隆对象并省略值。

如何修复以下代码以克隆除值之外的所有内容?

// replaces the index of each element to the giving index. so Title[0][name] will become Title[index][name]...
window.getContent = function (html, index) {
    return html.replace(/_\d+__/g, '_' + index + '__')
        .replace(/\[\d+\]/g, '[' + index + ']');
}

$(function(){

    $('#addRow').click(function(){

        // find the first row inside #container
        // clone it, find any input inside of it and set its value to empty string
        var template = $('#container .row').first().clone().find(':input').val('').end();

        // find the current count of the rows inside the container
        var index = $('#container .row').length;

        // replace the index inside the element name to the correct index
        var content = getContent(template.prop('outerHTML'), index);

        // append the new element on to the container
        $('#container').append(content);
    });
});

这是一个JS Fiddler使用上面的代码

最佳答案

尝试:

var template = $('#container .row').first().clone().find(':input').attr('value','').end();

应该为你做。

问题是 val 不会处理 default value 属性,这就是为什么需要 attr 的原因。

查看working here

关于javascript - 如何使用 jQuery 重置克隆对象的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52470367/

相关文章:

javascript - 基于 rxjs 中的时间处理事件流

javascript - 如何将 JSP 中的 ResultSet 对象发送回 HTML (JavaScript)?

Javascript 转换真/假值字符串文本

javascript - 如何让一些暴露模块代码仅在 DOM 准备好后运行?

php - 单选按钮显示悬停在两个单选按钮之间使用 jquery

javascript - 切换字段类型属性

javascript - 连续循环滚动(无 jQuery)

javascript - 如何在 jquery 对话框中添加日期选择器

jquery - 如何将最大行数设置为文本区域输入标签?

javascript - 如何用单选按钮点击填充 Jquery UI 进度条