javascript - 如何复制一个元素的所有属性并将它们应用到另一个元素?

标签 javascript jquery

如何将一个元素的属性复制到另一个元素?

HTML

<select id="foo" class="bar baz" style="display:block" width="100" data-foo="bar">...</select>

<div>No attributes yet</div>

JavaScript

var $div = $('div');
var $select = $('select');

//now copy the attributes from $select to $div

最佳答案

您可以使用 native Node#attributes属性:http://jsfiddle.net/SDWHN/16/ .

var $select = $("select");
var $div = $("div");

var attributes = $select.prop("attributes");

// loop through <select> attributes and apply them on <div>
$.each(attributes, function() {
    $div.attr(this.name, this.value);
});

alert($div.data("foo"));

关于javascript - 如何复制一个元素的所有属性并将它们应用到另一个元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6753362/

相关文章:

javascript - 在 CryptoJS 中创建共享 key 签名失败

javascript - KoJs : bind a dynamic number of text boxes to elements of an array

javascript - 从javascript提高单选按钮CheckedChanged

javascript - 附加 HTML 转义文本 : jQuery

javascript - Protractor :缩小

javascript - 使用 jQuery 克隆 HTML 并删除一些节点

php - 双击编辑 Kendo Grid incell 或内联编辑

javascript - SVG位移贴图过滤器

php - Ajax 调用同步运行

javascript - 在JavaScript中隐藏所有id