Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/87.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用Jquery获取正文中的任何文本节点_Jquery_Text_Nodevalue_Dom Node - Fatal编程技术网

使用Jquery获取正文中的任何文本节点

使用Jquery获取正文中的任何文本节点,jquery,text,nodevalue,dom-node,Jquery,Text,Nodevalue,Dom Node,希望有人能帮忙。我需要抓取身体内的任何文本节点。即使它不包含在任何其他元素中 我试过: $("p, div, html, body").each(function(){ $(this).contents().filter(function() { var regExText = /(\w|\d|,|;|&)/; if (this.nodeType == 3 &am

希望有人能帮忙。我需要抓取身体内的任何文本节点。即使它不包含在任何其他元素中

我试过:

$("p, div, html, body").each(function(){
    $(this).contents().filter(function() {
        var regExText = /(\w|\d|,|;|&)/;                                           
        if (this.nodeType == 3 && regExText.test(this.nodeValue)) {
            $(this).wrap('<span></span>');
            }
      });
});
$(“p,div,html,body”)。每个(函数(){
$(this.contents().filter(function()){
var regExText=/(\w |\d |,| |&)/;
if(this.nodeType==3&®extextext.test(this.nodeValue)){
$(此).wrap(“”);
}
});
});

这是在Ps和DIV中抓取它们,而不是在身体本身。

这不是你想要的

$('body').text();

你所拥有的应该有用。我想说的是,没有必要在选择器中包含
html
,但是,在
元素之外是否真的有任何东西需要在
中处理?

contents()
将只返回您指定的标记的子元素-p、div、html和body。例如,在td或h1标记中找不到文本节点

使用jQuery获取
标记内所有文本节点的一种方法是搜索body及其子代的子代

$("body, body *").contents().filter(function() {
    // if this is a text node and matches regex
    // then do something to it
}

您可以找到其他各种非jQuery的方法来获取其中的所有文本节点。

为什么不清理HTML呢

var strInputCode=$("body").html();
var strTagStrippedText = strInputCode.replace(/<\/?[^>]+(>|$)/g, "");
alert("Output text:\n" + strTagStrippedText);  
var strInputCode=$(“body”).html();
var strTagStrippedText=strInputCode.replace(/]+(>|$)/g,“”;
警报(“输出文本:\n”+strTagStrippedText);

我必须承认,可能是$(“body”).text()做了这件事

哪个是正确答案?;-)