我们还可以尝试扩展 jQuery 原型 ( $.fn
) 对象,以提供可以链接到 jQuery() 函数的新方法。
这是@pimvdb 解决方案的扩展,提供了一个复制所有属性的函数
用法如下:
$(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/提供了一个示例
希望这可以帮助。