天空小小岛技术论坛

 找回密码
 注册
搜索
查看: 5545|回复: 1
打印 上一主题 下一主题

innerHTML与innerText的用法与区别

[复制链接]
跳转到指定楼层
1#
八号 发表于 2009-10-3 12:19:26 | 只看该作者 回帖奖励 |倒序浏览 |阅读模式
用法:

<div id="test">
   <span style="color:red">test1</span> test2
</div>

在JS中可以使用:

test.innerHTML:

  也就是从对象的起始位置到终止位置的全部内容,包括Html标签。

  上例中的test.innerHTML的值也就是“<span style="color:red">test1</span> test2 ”。

test.innerText:

  从起始位置到终止位置的内容, 但它去除Html标签

  上例中的text.innerTest的值也就是“test1 test2”, 其中span标签去除了。

test.outerHTML:

  除了包含innerHTML的全部内容外, 还包含对象标签本身。

  上例中的text.outerHTML的值也就是<div id="test"><span style="color:red">test1</span> test2</div>


完整示例:

<div id="test">
   <span style="color:red">test1</span> test2
</div>

<a href="javascript:alert(test.innerHTML)">innerHTML内容</a>
<a href="javascript:alert(test.innerText)">innerText内容</a>
<a href="javascript:alert(test.outerHTML)">outerHTML内容</a>

特别说明:

  innerHTML是符合W3C标准的属性,而innerText只适用于IE浏览器,因此,尽可能地去使用innerHTML,而少用innerText,如果要输出不含HTML标签的内容,可以使用innerHTML取得包含HTML标签的内容后,再用正则表达式去除HTML标签,下面是一个简单的符合W3C标准的示例:

<a href="javascript:alert(document.getElementById('test').innerHTML.replace(/<.+?>/gim,''))">无HTML,符合W3C标准</a>

-------------------------------------------------------------------------------------------------------------------------------

<html>
<head></head>
<frameset frameborder="yes" frameborder="1" rows="40%,*">
<frame name="top" src="1.html">
<frame name="bottom" src="2.html">
</frameset>
</html>

<html>
<head>
<script language="javascript">
function init()
{   
    var aaa = parent.window.frames[0].document.body.innerHTML;
    alert(aaa);
}
</script>
</head>
<body>
<p align="center">nothing</p>
<p align="center"><input type="button" onclick="init()"; value="click"></p>
</body>
</html>

<html>
<center>汽车 房产 女人</center>
</html>
2#
tkxd 发表于 2011-3-11 10:21:45 | 只看该作者
本帖最后由 tkxd 于 2011-3-11 10:22 编辑

test.innerHTML: 也就是从对象的起始位置到终止位置的全部内容,包括Html标签。
test.innerText: 从起始位置到终止位置的内容, 但它去除Html标签.



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

本版积分规则

小黑屋|手机版|Archiver|天空小小岛  |京ICP备2025130156号|

GMT+8, 2025-6-22 04:46 , Processed in 0.095982 second(s), 18 queries , Gzip On.

Powered by Discuz! X3.1

© 2001-2013 Comsenz Inc.

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