大众世界 world of demotic + 社区新动力

 找回密码
 注册会员
搜索
查看: 5755|回复: 0

[Javascript] 如何让 FireFox 也支持 outerHTML

[复制链接]
发表于 2010-12-10 16:27:44 | 显示全部楼层 |阅读模式
  1. 假设要获取<p id="outerID">sdfdsdfsd</p> 的 P的outerHTML
  2. 代码:
  3. var _p = document.getElementById('outerID');
  4. _P = _P.cloneNode();
  5. var _DIV = document.createElement();
  6. _DIV.appendChild(_P);
  7. alert(_DIV.innerHTML); 就是P的outerHTML;
复制代码
但这样做局限性很大,只能针对这一个标签进行操作。不方便多次使用。为了解决这个问题,我们只有用DOM原型扩展方法解决
  1. if(typeof(HTMLElement)!="undefined" && !window.opera)
  2. {
  3.     HTMLElement.prototype.__defineGetter__("outerHTML",function()
  4.     {
  5.         var a=this.attributes, str="<"+this.tagName, i=0;for(;i<a.length;i++)
  6.         if(a[i].specified)
  7.             str+=" "+a[i].name+'="'+a[i].value+'"';
  8.         if(!this.canHaveChildren)
  9.             return str+" />";
  10.         return str+">"+this.innerHTML+"</"+this.tagName+">";
  11.     });
  12.     HTMLElement.prototype.__defineSetter__("outerHTML",function(s)
  13.     {
  14.         var r = this.ownerDocument.createRange();
  15.         r.setStartBefore(this);
  16.         var df = r.createContextualFragment(s);
  17.         this.parentNode.replaceChild(df, this);
  18.         return s;
  19.     });
  20.     HTMLElement.prototype.__defineGetter__("canHaveChildren",function()
  21.     {
  22.         return !/^(area|base|basefont|col|frame|hr|img|br|input|isindex|link|meta|param)$/.test(this.tagName.toLowerCase());
  23.     });
  24. }
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册会员

本版积分规则

Archiver|手机版|小黑屋|Wod Inc. ( 蜀ICP备20000008号-8

GMT+8, 2024-5-11 01:03 , Processed in 0.104769 second(s), 30 queries .

Powered by Discuz! X3.5

Copyright © 2001-2023 Tencent Cloud.

快速回复 返回顶部 返回列表