- <script type="text/javascript">
- function test() {
- alert(document.getElementById("div1").innerText);
- }
- </script>
- <div id="div1">Hello world!</div>
- <input type="button" value="OK" onclick="test();" />
在IE下,正常弹出“Hello world!”;而在firefox中,弹出的是“undefined”的未定义错误;
现在用javascript编写这样的一段代码
- try
- {
- HTMLElement.prototype.__defineGetter__ ("innerText", function ()
- {
- var anyString = "";
- var childS = this.childNodes;
- for(var i = 0; i < childS.length; i ++ )
- {
- if(childS[i].nodeType == 1)anyString += childS[i].tagName == "BR" ? '"n' : childS[i].innerText;
- else if(childS[i].nodeType == 3)anyString += childS[i].nodeValue;
- }
- return anyString;
- }
- );
- }
- catch(e)
- {
- }
本文介绍了一种解决跨浏览器innerText兼容性问题的方法。通过使用JavaScript动态为HTMLElement原型添加innerText属性,使得在不支持该属性的Firefox等浏览器上也能正确获取元素的文本内容。
198

被折叠的 条评论
为什么被折叠?



