简体   繁体   English

如何使用jQuery从给定HTML元素下的给定类的所有元素中提取文本

[英]How to extract text from all elements of given class under given HTML element with jQuery

When I do this: 当我这样做时:

var elem = $(".region_box");
text = elem.find(".my_text").html();

I can get text from the first element deep below "elem" with class "my_text" which it finds. 我可以通过找到的类“ my_text”从“ elem”下面的第一个元素中获取文本。

But there are many elements of the class "actual_text" below elem and I want to combine the text from all of them. 但是elem下面的类“ actual_text”中有很多元素,我想将所有元素的文本组合在一起。 How would I do it? 我该怎么办? I am new to jQuery and I searched around for solution for long time, but neither of them worked for me. 我是jQuery的新手,我一直在寻找解决方案很长时间,但它们都不适合我。 Perhaps I am using this each() function incorrectly. 也许我不正确地使用了这个each()函数。 I would very much appreciate any help. 非常感谢您的帮助。

You can use the jQuery.each 您可以使用jQuery.each

var text = '';

var elms = $(".region_box .my_text").each(function () {
    text = text + $(this).text(); // use .html() if you actually want the html
});

Define a variable to hold the new string, select all of the elements you wish to extract, chain that with .each() and add the contents of the text node for that element to the variable you created to hold the new string. 定义一个变量以容纳新字符串,选择所有要提取的元素,将其与.each()链接,并将该元素的文本节点的内容添加到为保留新字符串而创建的变量中。

( Demo ) 演示

var text = "";
$(".region_box .my_text").each(function(){ text += " " + $(this).text(); });

try something using jquery .map() method like this, 尝试使用jquery .map()这样的方法

text = $('.region_box').find('.my_text').map(function() {
  return $(this).text();
}).get().join(',');

As the site said, "As the return value is a jQuery object, which contains an array, it's very common to call .get() on the result to work with a basic array." 正如该站点所说,“由于返回值是一个jQuery对象,它包含一个数组,因此在结果上调用.get()以使用基本数组是很常见的。”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM