【问题标题】:Removing comments and text nodes from jQuery collection从 jQuery 集合中删除注释和文本节点
【发布时间】:2011-12-10 19:25:23
【问题描述】:
$html = $("<!-- comment --> <p>text</p>");

像这样创建一个 jQuery 集合

$( [the comment], [text node], p )

我怎样才能只访问该段落? .find("p") 返回一个空集合

而且,为了加分,

$html = $("<p>text</p>");

像这样创建一个 jQuery 集合

$( p )

是否有一种故障安全的方法来获取 p,并且只有 p,无论评论是否存在都有效?

【问题讨论】:

    标签: javascript jquery comments textnode


    【解决方案1】:
    var p = $html.filter(function() { return this.nodeType === 1; });
    

    jsFiddle.

    【讨论】:

    • 返回一个空选择。不需要contents() 调用。
    【解决方案2】:

    最简单的方法是使用filter 和通用选择器*,它匹配所有元素。

    $html = $("<!-- comment --> <p>text</p>").filter('*');
    

    【讨论】:

    • 是的。 filter 在集合上工作,而 find 确实需要一个“根”DOM 节点才能开始。
    • 只获取p的内容,$('&lt;!-- comment --&gt; &lt;p&gt;text&lt;/p&gt;').filter('p');
    • @Jean-Charles 嗯,是的。我以问题的标题为例,以它的正文为例。
    【解决方案3】:

    试试这个demo。也许这不是你将要使用它的确切方式,但你明白了。

    <div class="text">
        <!-- comment -->
        <p>text</p>
    </div>
    
    var html = $('.text').html();
    html = $.trim(html.replace(/<!--(.*?)-->/ig, ''));
    alert(html);
    

    【讨论】:

    • 虽然严格来说它解决了问题,但我认为这有点偏离了重点。
    【解决方案4】:

    一种方法是像$html = $("&lt;!-- comment --&gt; &lt;p&gt;text&lt;/p&gt;");那样通过索引获取,你可以使用$($html[2])获取p标签。

    或

    $html = $("<!-- comment --> <p>text</p>");
    $target = new Object();
    for(key in $html){
        if(typeof $html[key] ===  'object' && $html[key].localName === 'p')
            $target = $html[key];
    }
    

    【讨论】:

    • 最好使用“nodeName”而不是“localName”。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-01
    • 1970-01-01
    • 2011-11-05
    • 2016-02-02
    相关资源
    最近更新 更多