怎样用jQuery自带方法/函数来获取outerHTML属性

如题所述

用jQuery自带方法/函数来获取outerHTML属性的方法:
1、定义方法outerHTML:

jQuery.fn.outerHTML = function(s) {
return s
? this.before(s).remove()
: jQuery("<p>").append(this.eq(0).clone()).html();
};

2、使用举例:
有如下html标签:<div id="xxx"><p>Hello World</p></div>获取Hello World的方法:
outerHTML('<p>Hello World</p>');
3、输出结果:
Hello World
温馨提示:内容为网友见解,仅供参考
第1个回答  2016-06-15
用jQuery自带方法/函数来获取outerHTML属性是需要重写jquery的outerHTML方法。
两种实现方法:
1、直接扩展outerHTML:
jQuery.fn.outerHTML = function(s) {
return s
? this.before(s).remove()
: jQuery("<p>").append(this.eq(0).clone()).html();
};

2、包装成匿名函数:
(function($) {
$.fn.outerHTML = function() {
return $(this).clone().wrap('<div></div>').parent().html();
};
})(jQuery);
相似回答