innerHTML() 是原生的,它返回 DOM 节点的内容(例如 <span>I live inside a div.</span>
)。outerHTML() 不是,它将包括当前 DOM 节点(例如 <div><span>I live inside a div.</span></div>
)。这是一个可链式 jQuery 版本,用于执行此操作。
$.fn.outerHTML = function(){
// IE, Chrome & Safari will comply with the non-standard outerHTML, all others (FF) will have a fall-back for cloning
return (!this.length) ? this : (this[0].outerHTML || (
function(el){
var div = document.createElement('div');
div.appendChild(el.cloneNode(true));
var contents = div.innerHTML;
div = null;
return contents;
})(this[0]));
}
我是不是漏了什么,这似乎是无必要地使事情复杂化,为什么不能像这样编写
https://gist.github.com/3707775 ?
此页面上的代码片段返回一个可链式 jQuery 对象。
这是不正确的,只有在集合中没有元素时,它才会返回一个可链式 jQuery 对象
return (!this.length) ? this : (this[0].outerHTML || (function(){ ... })());
如果 jQuery 集合为空(长度为 0),则它将返回
this
,即可链式的 jQuery 对象。否则,它将尝试返回本机 htmlouterHTML
属性。如果本机 htmlouterHTML
属性为 null,则它将调用该函数,该函数也返回一个字符串,而不是一个 jQuery 对象。此代码片段也不会对集合中的每个元素执行此操作,它只对第一个元素 (
this[0]
) 执行此操作。但是,这很有道理,因为返回 html 字符串数组会很奇怪,这些字符串将不是 jQuery 对象。这里使用的 el 是什么? 迷路了…
它是 “this[0]”。 关于立即调用函数表达式的更多信息
我们如何调用该函数