FireFox和非IE浏览器的innerText(非innerHtml)JavaScript实现。

In the sick, twisted word of cross-browser DOM-based JavaScript, sometimes you need to get the contents of an element. You usually use element.innerHTML, but often you don't want any existing sub-tags that might be in there. You want .innerText! But, innerText is only available on IE. Poop.

在基于DOM的跨浏览器JavaScript中,有时您需要获取元素的内容。 您通常使用element.innerHTML,但通常您不希望在其中存在任何现有的子标记。 您想要.innerText! 但是,innerText仅在IE上可用。 船尾。

So, I needed this today, and my buddy Stuart found a solution here. Sick, yes. Twisted, yes. Works, yes. Moving on.

因此,我今天需要这个,而我的好友Stuart在这里找到了解决方案。 病了,是的。 扭曲,是的。 可以,是的。 继续。

    <script type="text/javascript">
      var regExp = /<\/?[^>]+>/gi;
      function ReplaceTags(xStr){
        xStr = xStr.replace(regExp,"");
        return xStr;
      }
    </script>

<script type =“ text / javascript”> var regExp = / <\ /?[^>] +> / gi; 函数ReplaceTags(xStr){ xStr = xStr.replace(regExp,“”); 返回xStr; } </ script>

All you need to do is pass it a string and it returns the string stripped of the tags. An example is shown below to grab the text from a div without the tags.

您需要做的就是将一个字符串传递给它,然后返回去除了标签的字符串。 下面显示了一个示例,该示例从没有标签的div抓取文本。

<html>
  <head>
    <script type="text/javascript">
      var regExp = /<\/?[^>]+>/gi;
      function ReplaceTags(xStr){
        xStr = xStr.replace(regExp,"");
        return xStr;
      }
    </script>
  </head>
  <body>
    <div id="test">
      <span id="span1">Test <u><b>Test</b></u> Test <br/><a href="#">Wow</a>!</span>
    </div>
    <script type="text/javascript">
      var xContent = document.getElementById("test").innerHTML;
      var fixedContent = ReplaceTags(xContent);
      alert(fixedContent);
    </script>
  </body>
</html>
[Eric's Weblog]

<html> <头> <script type =“ text / javascript”> var regExp = / <\ /?[^>] +> / gi; 函数ReplaceTags(xStr){ xStr = xStr.replace(regExp,“”); 返回xStr; } </ script> </ head> <身体> <div id =“ test”> <span id =“ span1”>测试<u> <b>测试</ b> </ u>测试<br/> <a href="#">哇</a>!</ span> </ div> <script type =“ text / javascript”> var xContent = document.getElementById(“ test”)。innerHTML; var fixedContent = ReplaceTags(xContent); alert(fixedContent); </ script> </ body> </ html> [ Eric的博客]

翻译自: https://www.hanselman.com/blog/a-javascript-implementation-of-innertext-not-innerhtml-for-firefox-and-nonie-browsers

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值