将一个元素的所有属性分配给另一个元素
Assigning all the attributes of an element to another
我编写此代码是为了用下拉列表替换具有特定数据属性的页面的所有元素。假设我是否有:
<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% 保证我的代码适合你的目的......
相关文章:
- javascript来显示元素属性
- 自定义HTML元素属性未显示-Web组件
- 主元素属性?(或技术)
- 使用模板后,使用Angular获取元素属性值
- 如何从不同范围外的元素属性中获取求值表达式
- 可以't访问元素属性(如果已明确设置)
- 传递引用 jQuery 后无法访问元素属性
- 如何替换元素属性中的部分文本
- 添加新元素属性
- 如何使用jQuery访问父元素属性
- 使用jQuery.attr()方法获取元素属性
- 修改时,哪些DOM元素属性会导致浏览器执行回流操作
- Javascript数据将元素属性绑定到URL中的锚href
- 初始化可从元素属性值观察到的Knockout
- 获取内联样式中的元素属性
- 如何在 html 元素属性中使用 Angular 2 外推法
- 将元素属性与 javascript 折叠方法结合使用时,引导折叠无法正常工作
- 如何观察聚合物元素属性值从索引.html的变化
- 使用 JavaScript 修改 DOM 元素属性
- 聚合物节点到元素属性