4
$html = $("<!-- comment --> <p>text</p>");

像这样创建一个 jQuery 集合

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

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

而且,为了加分,

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

像这样创建一个 jQuery 集合

$( p )

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

4

4 回答 4

7

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

$html = $("<!-- comment --> <p>text</p>").filter('*');
于 2011-10-19T10:19:06.357 回答
1
var p = $html.filter(function() { return this.nodeType === 1; });

js小提琴

于 2011-10-19T10:18:40.693 回答
0

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

<div class="text">
    <!-- comment -->
    <p>text</p>
</div>

var html = $('.text').html();
html = $.trim(html.replace(/<!--(.*?)-->/ig, ''));
alert(html);
于 2011-10-19T10:26:25.957 回答
0

一种方法是通过索引获取,就像$html = $("<!-- comment --> <p>text</p>");你可以使用$($html[2]).

或者

$html = $("<!-- comment --> <p>text</p>");
$target = new Object();
for(key in $html){
    if(typeof $html[key] ===  'object' && $html[key].localName === 'p')
        $target = $html[key];
}
于 2011-10-19T10:29:14.443 回答