0

当我将鼠标放在 H1 上时,我试图将 H1 的内容写入 div,但只得到 [Object HTMLHeadingElement],而不是文本本身。我是一个初学者,我正在尝试使用 innerHTML 属性。谢谢你们!

HTML code:

<h1 id="phrase" onmouseover="writeInDiv2()">Hi all</h1>

JavaScript code:

var text = document.getElementById("phrase");

function writeInDiv2(){
    if(div2.style.display != "none"){
        div2.innerHTML = text;
    }
}
4

2 回答 2

6

您有三个选项来获取文本内容:

// 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 小提琴演示

于 2013-04-01T10:51:53.163 回答
1

尝试div2.innerHTML = text.innerHTML;

于 2013-04-01T10:51:04.597 回答