javascript - 将一个元素的所有属性分配给另一个元素

标签 javascript jquery html dom

我编写这段代码是为了用下拉菜单替换页面中具有特定数据属性的所有元素。假设我有过:

<span data-what="partyBox"></span>

它将被替换为下拉菜单。该代码运行良好,但有一个异常(exception);稍后我想分配当前标签的所有属性(例如所有数据属性或任何其他分配的属性),即本例中的 span 标签分配给我创建的下拉列表。但是我在实现这一点时遇到了问题,即它没有将所有这些属性应用于下拉列表。这是我的代码:

var mould = {

    partyBox        :   $.parseHTML('<select name="mouldedParty"><option value="-1" selected disabled>Select Party</option></select>'),

    init            :   function (){ },

    process         :   function (container) {
                            var pBox     = $(mould.partyBox);
                            var pBoxes   = $(container).find('[data-what=partyBox]');

                            pBox.css({
                                'padding'    : '10px',
                                'border'     : '1px solid #ccc',
                                'background' : '#368EE0',
                                'color'      : 'white',
                                'cursor'     : 'pointer'
                            });

                            $(pBoxes).each(function(index, elem){
                                var attributes = elem.attributes;
                                var test = $(elem).replaceWith(pBox);
                                test.attributes = attributes;

                            });

                            // pBoxes.replaceWith(pBox);

                        }
};

mould.process('body');

任何人都可以告诉我这段代码有什么问题吗?为什么它不将 span 标记的所有属性应用于下拉列表,尽管我已经使用这些行进行替换

            var attributes = elem.attributes;
            var test = $(elem).replaceWith(pBox);
            test.attributes = attributes;

最佳答案

您不能设置元素的 attributes 属性。您所能做的就是将属性从一个元素复制到另一个元素。

这样的代码可能是一个解决方案:

$(pBoxes).each(function (index, elem) {
    var newBox = pBox.clone(true, true)[0]; // get a simple DOM element

    // loop through the old element's attributes and give them to the new element
    for (var name in elem.attributes) {
        newBox.setAttribute(name, elem.attributes[name].value);
    }

    // replace the old element with the new one
    var test = $(elem).replaceWith(newBox);
});

我承认我发现你的代码有点困惑,所以我不能 100% 保证我的代码适合你的目的...

关于javascript - 将一个元素的所有属性分配给另一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19837049/

相关文章:

javascript - 为什么某些字体的元素的 scrollHeight 和 clientHeight 不一样?

javascript - 如何使用 javascript 或 Angular 将一个数组的每个元素添加到其他数组中的相应元素

javascript - 具有作用域的 JQuery 命名函数

c# - 使用 ASP.NET 和 C# 按页显示记录

javascript - 设置动态创建的文本框中文本的格式

javascript - 两个 div 和 div 子元素之间的键盘箭头导航

jquery - 循环具有固定位置的水平滚动 div

html - 命名表格有什么意义?

html - 如何将文本放置在与图像相同的高度

javascript - 在一个页面上同时显示来自 Google 的多个搜索的最佳方式?