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 
	
 您可以使用本地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")); 
jsfiddle的工作解决scheme
编辑
更新了jsfiddler
使用Javascript
 $(function(){ var destination = $('#adiv').eq(0); var source = $('#bdiv')[0]; for (i = 0; i < source.attributes.length; i++) { var a = source.attributes[i]; destination.attr(a.name, a.value); } }); 
HTML
 <div id="adiv" class="aclass">A class</div> <div id="bdiv" class="bclass">B class</div> 
 这是将#bdiv属性复制到#adiv 。 
很简单
 function cloneAttributes(element, sourceNode) { let attr; let attributes = Array.prototype.slice.call(sourceNode.attributes); while(attr = attributes.pop()) { element.setAttribute(attr.nodeName, attr.nodeValue); } } 
 我们也可以尝试扩展jQuery原型( $.fn )对象来提供一个可以链接到jQuery()函数的新方法。 
这里是@ pimvdb解决scheme的扩展,提供了一个复制所有属性的函数
用法如下所示:
  $(destinationElement).copyAllAttributes(sourceElement); 
扩展函数可以这样定义:
 (function ($) { // Define the function here $.fn.copyAllAttributes = function(sourceElement) { // 'that' contains a pointer to the destination element var that = this; // Place holder for all attributes var allAttributes = ($(sourceElement) && $(sourceElement).length > 0) ? $(sourceElement).prop("attributes") : null; // Iterate through attributes and add if (allAttributes && $(that) && $(that).length == 1) { $.each(allAttributes, function() { // Ensure that class names are not copied but rather added if (this.name == "class") { $(that).addClass(this.value); } else { that.attr(this.name, this.value); } }); } return that; }; })(jQuery); 
一个例子可以在http://jsfiddle.net/roeburg/Z8x8x/find
希望这可以帮助。
一个非jQuery解决scheme:
 function copy(element){ var clone = document.createElement(element.nodeName); for(key in element){ clone.setAttribute(key,element[key]); } return clone; } 
它复制方法和其他你可能不需要的东西,但希望你不介意。 这段代码很小,很简单。
自Firefox 22以来,不再支持Node.attributes(不由其他浏览器实现并从规范中删除)。 它仅在Element(Element.attributes)上受支持。
你可以试试这个:
 function copyAttributes(from, to) { $($(from)[0].attributes). each(function(){$(to).attr(this.nodeName, this.nodeValue);}); return $(to); }; 
return语句可以让你写下如下的东西:
 copyAttributes(some_element, $('<div></div>')).append(...) ... 
希望这可以帮助。
 $("div").addClass($('#foo').attr('class'));