innerHTML和innerText怎么區分?
損失函數
2016-07-08 15:07:43
TA貢獻319條經驗 獲得超234個贊
<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)">inerHTML內容</a>
共同點:innerHTML和innerText都會把元素內內容替換掉。
不同點:
1,innerHTML:?
也就是從對象的起始位置到終止位置的全部內容,包括Html標簽。?
上例中的test.innerHTML的值也就是“<span style="color:red">test1</span>?
test2 ”。?
2,innerText:?
從起始位置到終止位置的內容, 但它去除Html標簽?
上例中的text.innerTest的值也就是“test1 test2”, 其中span標簽去除了。?
值得注意的是,innerHTML是符合W3C標準的屬性,而innerText只適用于IE瀏覽器,因此,盡可能地去使用innerHTML,而少用innerText,如果要輸出不含HTML標簽的內容,可以使用innerHTML取得包含HTML標簽的內容后,再用正則表達式去除HTML標簽。
TA貢獻345條經驗 獲得超309個贊
innerHTML可以向文檔中輸入標簽,而 innerText 只能輸入文字,例子如下:
<!doctype?html>
<html?lang="en">
<head>
<meta?charset="UTF-8"?/>
<title>Document</title>
<style?type="text/css">
#div1,#div2{
width:?200px;
height:?200px;
border:?1px?solid?red;
}
</style>
</head>
<body>
<div?id="div1"></div>
<div?id="div2"></div>
</body>
<script>
var?div1?=?document.getElementById('div1');
var?div2?=?document.getElementById('div2');
div1.innerHTML?=?'div<p>p?標簽</p>';
div2.innerText?=?'div<p>p?標簽</p>';
</script>
</html>望采納!
舉報