【问题标题】:jQuery get the text of all elements in a pagejQuery获取页面中所有元素的文本
【发布时间】:2012-03-20 23:44:54
【问题描述】:

我想获取所有元素的文本。我在这里使用此代码:

$('*').filter(function()
{
    if(($(this).text().lenght>0)&&($(this).text().lenght<100))
    {
        return true;
    }
    else
    {
        return false;
    }
}).each(function()
{
    console.log($(this).text());
});

我尝试只显示短文本,因为 .text() 有时会返回 html 代码,但它根本不起作用。

【问题讨论】:

  • 如果是复制粘贴,那么您的长度拼写错误。
  • 你不是第一个做出明显但不知何故隐藏得很好的错字的人;)

标签: jquery text elements


【解决方案1】:

更简单:$('body').text() 为您提供页面上的整个文本。

如果您需要遍历所有文本节点,请参见此处:How do I select text nodes with jQuery?

【讨论】:

  • 是的,但我需要单独的文本元素。例如:带有文本“hi”的div,带有文本“user”的div,等等。我需要在最后有一个包含此元素文本的数组。这就是我使用 $('*') 的原因
  • 查看我的答案中的链接如何遍历文档中的所有文本节点。它比你想象的要复杂得多。
  • 谢谢大家的回答。我已经修复了我的功能,并让我想做的事情变得更加复杂。我也会浏览你的链接。
【解决方案2】:

length应该有拼写错误

$('*').filter(function()
{
    if(($(this).text().length>0)&&($(this).text().length<100))
    {
        return true;
    }
    else
    {
        return false;
    }
}).each(function()
{
    console.log($(this).text());
});

【讨论】:

    【解决方案3】:

    无法检查这是否适用于 atm,但这样的东西应该是你所追求的,可能需要一些修改来过滤掉脚本和东西。

    $('body').children().each(function(index) {
         yourarray[index] = $(this).text();
    });
    

    编辑:试了一下,发现它只需要第一个孩子,而不是孙子,还包括很多空格和其他东西,我没有时间为你编写整个函数,但至少这是一个好的开始. .find('*') 获取文档中的所有元素。

    $("body").find('*').each(function (index) {
        //checks that the text isnt empty, no need to store that.
        if ($(this).text() != '') {
            //stores the elements text inside a temp variable, 
            //trims it from whitespaces and console.logs the results.
            temp = $(this).text();
            yourarray[index] = $.trim(temp);
            console.log(index+': '+yourarray[index]);
        }
    });
    

    【讨论】:

      【解决方案4】:

      也许是这样的:

      $("body").find().each(function () {
          if ($(this).text != undefined) {
              ...
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-05-05
        • 1970-01-01
        • 1970-01-01
        • 2010-11-15
        • 2018-04-21
        • 1970-01-01
        • 2012-07-06
        • 2015-03-09
        相关资源
        最近更新 更多