您有三个选项来获取文本内容:
// Webkit, Mozilla, Opera (and other standards-compliant) browsers
var text = document.getElementById("phrase").textContent;
// Microsoft Internet Explorer (though this might have changed in IE 10)
var text = document.getElementById("phrase").innerText;
// Possibly works, though assumes the h1 contains only a text-node
var text = document.getElementById("phrase").firstChild.nodeValue;
为了提高效率,使用以下 HTML:
<h1 onmouseover="writeInDiv2(this, 'div2')">Hi all</h1>
<h1 onmouseover="writeInDiv2(this, 'div2')">Another message</h1>
<div id="div2"></div>
我建议:
function writeInDiv2(el, textInto){
var div2 = textInto.nodeType === 1 ? textInto : document.getElementById(textInto),
text = el.textContent ? el.textContent : el.innerText;
while (div2.firstChild){
div2.removeChild(div2.firstChild);
}
div2.appendChild(document.createTextNode(text));
}
JS 小提琴演示。