javascript 获取元素 jquery 中的第一行文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7381012/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:55:17  来源:igfitidea点击:

getting the first line of text in an element jquery

javascriptjqueryhtml

提问by Harry

I have an example element like this:

我有一个这样的示例元素:

<div id="element">
  Blah blah blah.
  <div>Header</div>
  ...
</div>

it can also look like this:

它也可以是这样的:

<div id="element">
  <span>Blah blah blah.</span>
  <h4>Header</h4>
  ...
</div>

I want to get the first line (defining line loosely) (Blah blah blah.) of text inside the element. It might be wrapped inside a child element or just be naked textnode. How do I do that? Thanks.

我想获得元素内文本的第一行(松散地定义行)(废话废话。)。它可能被包裹在一个子元素中,或者只是一个裸文本节点。我怎么做?谢谢。

回答by user113716

Use the contents()[docs]method to get all children, including text nodes, filter out any empty (or whitespace only) nodes, then grab the first of the set.

使用contents()[docs]方法获取所有子节点,包括文本节点,过滤掉任何空(或仅空白)节点,然后获取集合中的第一个。

var first_line = $("#element")
                       .contents()
                       .filter(function() { 
                           return !!$.trim( this.innerHTML || this.data ); 
                       })
                       .first();

text node:http://jsfiddle.net/Yftnh/

文本节点:http : //jsfiddle.net/Yftnh/

element:http://jsfiddle.net/Yftnh/1/

元素:http : //jsfiddle.net/Yftnh/1/

回答by simoncereska

Here is idea for you. Of course if there is h4 element before line you want to get:

这是给你的想法。当然,如果您想要获得的行前有 h4 元素:

var content = $('#element').html();
var arr = content.split('<h4>');
console.log(arr[0]);

回答by Maximilian Hils

var myElement = $("#element");
while(myElement.children().length > 0)
{
   myElement = myElement.children().first();
}
var firstText = myElement.text();

Assuming that the text is correctly wrapped inside an element, of course. You might check whether there's text before the first element:

当然,假设文本正确地包裹在元素中。您可以检查第一个元素之前是否有文本:

/\s*</.test(myElement.html())

回答by Mo D Genesis

the counter starts at 1

计数器从 1 开始

myElement.text().split('\n')[1]

回答by clem

first get the content of the element

首先获取元素的内容

var content = $('#element').html();

then split the text into an array using line break

然后使用换行符将文本拆分为一个数组

tmp = content.split("\n");

the first part of the array is the first line of the element

数组的第一部分是元素的第一行

var firstLine = tmp[0];