使用jQuery选择包含在注释中的元素

Use jQuery to select an element that is contained within a comment

本文关键字:元素 注释 jQuery 选择 包含 使用      更新时间:2023-09-26

我有一个奇怪的问题,我想知道这是否可能。

我正在解析DOM,有这样一个元素:

<!-- <a class="pager" title="next" href="www.text.com">NEXT</a> -->

我需要能够使用jQuery选择此元素并返回其href值。我试过了:

$('a.pager[title="Next"]').attr('href');

,但没有用-从这里阅读选择HTML评论与jQuery,似乎jQuery只能选择元素与特定的nodetype

是否可以从上面的HTML元素返回值www.text.com ?为了让事情变得更棘手,我需要在不依赖jQuery插件的情况下完成它-本机Javascript或纯jQuery。

下面的代码返回整个注释(以及该页上所有其他注释中包含的文本):

$("*")
    .contents()
    .filter(function(){ return this.nodeType == 8;})
    .each(function(){ alert(this.nodeValue);});

但我只需要返回a href的值,而没有其他注释。想法吗?

实际上,你所要做的就是修剪它:

var markup = $("*").contents().filter(function(){ 
    return this.nodeType == 8;
}).get(0).nodeValue;
var href = $($.trim(markup)).attr('href');

小提琴

编辑:

让它更具体你总是可以做一些字符串匹配:

var markup = $("*").contents().filter(function(){ 
    return this.nodeType == 8 && this.nodeValue.indexOf('class="pager"') != -1;
});

编辑:

你也可以这样做:

var href = $.map($("*").contents(), function(el) {
    var html   = $.parseHTML( $.trim(el.nodeValue) ),
        anchor = $('<div />').append(html).find('a.pager[title="next"]');
    return el.nodeType === 8 && anchor.length ? anchor.attr('href') : null;
});

小提琴

选择注释后,需要将其文本内容解析为HTML,然后才能可靠地遍历编码的DOM:

var matches = [];
$("*").contents().each(function(){
  if(this.nodeType != 8) return;
  var $div = $("<div>");
  $div.append(this.nodeValue);
  $div.find("a.pager[title='next']").each(function(){
    //replace $(this).attr("href") with this.href if you don't mind
    //relative URLs getting converted to absolute URLs
    matches.push($(this).attr("href"))
  });
});
$("*")
    .contents()
    .filter(function(){ return this.nodeType == 8;})
    .each(function(){
        var regex = new RegExp('href='"(.*)'"','g');
        var hrefValue = regex.exec(this.nodeValue)[1];
        alert(hrefValue);
    });