gpt4 book ai didi

jquery - 使用 jQuery 而不是innerHTML 获取innerText

转载 作者:行者123 更新时间:2023-12-03 09:23:27 24 4
gpt4 key购买 nike

我有一个图标题,我想要其中的文本。这就是 chrome 元素检查器中的样子。由于某种原因,“innerHTML”以回车符开头,然后是很多空格。然而“innerText”看起来不错,所以我对此很感兴趣。

enter image description here

在网上我看到我必须使用 text() 方法来获取innerText,但它似乎给出了innerHTML:

console.log("-"+$(this).find("figcaption").text()+"-");

enter image description here

那么我怎样才能到达innerText呢?

最佳答案

当您创建 HTML 元素时,例如:

<p>Hello          World</p>

当浏览器呈现时,默认情况下会折叠空白。结果将是“Hello World”。数据的崩溃发生在浏览器渲染时。浏览器中包含的 DOM 模型维护实际文本,包括其中包含的任何空白。因此,您在屏幕上看到的内容可能与 DOM 中包含的数据不同。

可以通过名为“innerText”的 DOM 属性获得空白删除数据。

一个jsBin显示已提供数据的示例。

演示代码基本上是:

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"));
});
});

控制台将记录:

text: Hello      World
innerText: Hello World

从你原来的问题来看,使用 text() 方法返回 DOM 数据,而使用 prop("innerText") 返回计算的 innerText 浏览器构建的值。

关于jquery - 使用 jQuery 而不是innerHTML 获取innerText,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26720490/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com