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

Assigning all the attributes of an element to another

本文关键字:元素 属性 分配 另一个 一个      更新时间:2023-09-26

我编写此代码是为了用下拉列表替换具有特定数据属性的页面的所有元素。假设我是否有:

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

它将替换为下拉列表。代码运行良好,但有一个例外;稍后我想分配当前标签的所有属性(例如所有数据属性或任何其他分配的属性),即在这种情况下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% 保证我的代码适合你的目的......