2011-12-12 27 views
4

我發現這個功能(雖然,我忘了在哪裏):如何擴展JavaScript對象,使得本身不具備outerHTML瀏覽器,我可以將其定義?

function outerHTML(node){ 
    // if IE, Chrome take the internal method otherwise build one 
    return node.outerHTML || (
     function(n){ 
      var div = document.createElement('div'), h; 
      div.appendChild(n.cloneNode(true)); 
      h = div.innerHTML; 
      div = null; 
      return h; 
     })(node); 
} 

但此功能通過調用outerHTML(my_element)而不是my_element.outerHTML

我希望能夠延長一個javascript DOM元素對象,使得它具有outerHTML元素,但仍使用本地元素(如果存在)。我怎麼做?

我想這樣做的主要原因是因爲Firefox本身並沒有使用outerHTML方法,但我仍然想使用本地實現(如果可用),因爲它們經過了全面測試,我感覺我可以信任他們。

更新: @Raynos建議我不要爲outerHTML做上述工作,而應該做一些類似於outerHTML規範的工作。 我發現這一點: How do I do OuterHTML in firefox? ,它不會做.cloneNode,它可以在Firefox 8.0.1導致錯誤。
所以,我的解決辦法是這樣的,按照@Raynos:

if (!("outerHTML" in HTMLElement.prototype)) { 
    Object.defineProperty(HTMLElement.prototype, "outerHTML", { 
     get: getOuterHTML 
    }); 
} 


function getOuterHTML(){ 
    var parent = this.parentNode; 
    var el = document.createElement(parent.tagName); 
    el.appendChild(this.cloneNode(true)); 
    var shtml = el.innerHTML; 
    return shtml; 
} 

回答

8

你通常是這樣的:

if (!("outerHTML" in document.body)) { 
    Object.defineProperty(Element.prototype, "outerHTML", { 
     get: getOuterHTML, 
     set: setOuterHTML 
    }); 
} 

然後你讀在outerHTML specificationgetOuterHTMLsetOuterHTML功能實現它。

注意:我積極建議不要天真地執行outerHTML不符合規範的屬性。當您的「版本」工作方式與本地版本不同時,這會導致您在維護時遇到問題。特別是如果你添加propietory擴展或額外的「特色」,以您的版本

注意Object.defineProperty在舊的瀏覽器是不明確的。您可能需要使用墊片從es5-shim

+0

Raynos做得更好。檢查方法是否先存在。 ;) – nickytonline

+0

@nickyt還定義了實際的getter和setter,你增加一個功能,這意味着你必須做'elm.outerHTML();',而不是'elm.outerHTML' – Raynos

+0

正要約在您的實現作出評論。 – nickytonline

1

將它添加到HTML元素的原型

HTMLElement.prototype.outerHTML = function() { 
     // Your implementation of getting outerHTML 
} 
0

你可能想嘗試擴展節點基本對象,從中幾乎所有的DOM的延伸閱讀這裏的描述元素element - MDN或其他迴應嘗試的HTML元素也讀到這裏從MDN - HTMLElement

Element.prototype.outerHTML = function(){ console.log('hola'); }; 
HTMLElement.prototype.outerHTML = function(){ console.log('hola'); }; 

Raynos在評論中指出這裏是Spec article, which is encouraging to use Element

編輯:刪除節點引用

+0

[specification]( http://html5.org/specs/dom-parsing.html#outerhtml)實際上鼓勵你擴展'Element',很好的捕獲,但是把'outerHTML'放在'Node'上是不好的。 – Raynos

+0

謝謝你,我會編輯我的答案! – rroche

相關問題