JavaScript DOM操作案例封装innerText跟textContent函数(浏览器兼容)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> <style> div { width: 500px; height: 20px; border: 2px solid red; } </style> </head> <body> <input type="button" value="按钮" id="bt"/> <div id="dv">哇,好棒</div> <script src="common.js"></script> <script> //设置任意的标签中间的文本内容 function setInnerText(element, text) { //判断浏览器是否支持该属性 if (typeof element.textContent == "undefined") { element.innerText = text; } else { element.textContent = text; } } //获取任意标签中间的文本内容 function getInnerText(element) { if (typeof element.textContent == "undefined") { return element.innerText; } else { return element.textContent; } } //测试 // my$("bt").onclick = function () { // alert(getInnerText(my$("dv"))); // }; my$("bt").onclick = function () { setInnerText(my$("dv"), "真的很棒"); }; </script> </body> </html>