我有一个 figcaption,我想要其中的文字。这就是它在 chrome 中的元素检查器中的样子。出于某种原因,“innerHTML”以返回开始,然后是很多空格。然而,“innerText”看起来不错,所以我对此很感兴趣。
在线我看到我必须使用该text()
方法来获取innerText,但它似乎给出了innerHTML:
console.log("-"+$(this).find("figcaption").text()+"-");
那么我怎样才能到达innerText呢?
When you create an HTML element such as:
<p>Hello World</p>
When that is rendered by the browser, whitespace is collapsed by default. The result will be "Hello World". That collapsing of the data happens at browser rendering time. The DOM model contained within the browser maintains the actual text including any white spaces contained within it. As such, what you see on the screen may not be the same as the data contained within the DOM.
The white space stripped data is available via the DOM property called "innerText".
A jsBin sample showing the data has been supplied.
The demonstration code is basically:
HTML
<p id="here">Hello World</p>
<button>Show</button>
JavaScript
$(function() {
$("button").click(function() {
console.log("text: " + $("#here").text());
console.log("innerText: " + $("#here").prop("innerText"));
});
});
The console will log:
text: Hello World
innerText: Hello World
From your original question, the use of the text()
method returns the DOM data while the use of prop("innerText")
returns the calculated innerText
value that the browser built.