改变元素类型(jQuery)

起因

工作当中遇到个有点意思的技术需求:把某个div元素替换成a元素。本以为使用jQuery会有现成的API,类似$(element).changeType("a")啥的,一行代码搞定,结果没找到o(╯□╰)o,看来好久没用jQuery的后果就是喜欢意淫没有的API。自己动手,丰衣足食。

思路

  1. 获取要替换的元素特性集合,暂存到一个变量里。
  2. 构造新的元素,即目标元素,并将暂存的特性赋到该元素中。
  3. 使用jQuery API:replaceWith,将要替换的元素用新构造的元素替换之。

代码实现

1
2
3
4
5
6
7
8
9
10
//source element:div.from
var attrs = {};
var $srcEle = $("div.from");
$.each($srcEle[0].attributes, function(idx, attr) {
attrs[attr.nodeName] = attr.nodeValue;
});
var $targetEle = $("<a/>",attrs).append($srcEle.contents());
$(this).replaceWith(function() {
return $targetEle;
});

当然,为了更具通用性,可以做成一个插件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
(function($) {
$.fn.changeElementType = function(newType) {
this.each(function() {
var attrs = {};
$.each(this.attributes, function(idx, attr) {
attrs[attr.nodeName] = attr.nodeValue;
});
$(this).replaceWith(function() {
return $("<" + newType + "/>", attrs).append($(this).contents());
});
});
};
})(jQuery);

最后说一句

意淫没关系,或许正是开始创作的好契机。

微信环境下长按识别或保存

微信支付二维码
支付宝支付二维码