1

鉴于html:

<div id="t">
   <a class="xx">xx</a>
   <a class="yy">yy</a>
   <a class="zz">zz</a>
</div>

现在,如果我想获取类为xxor的链接zz,也就是说我想得到这个:

   <a class="xx">xx</a>
   <a class="zz">zz</a>

我试过这个:

$("#t a").each(function(){
  if($(this).is(".xx,.yy"){
    //here how to get the out the HTML of the current a element?
  }
});

有什么选择吗?

我注意到有两个答案,但似乎他们误解了我。

$("#t a").each(function(){
  if($(this).is(".xx,.yy"){
    //here I want to get the full HTML of the `a` element
    // That's to say, I want to get `<a class="xx">xx</a>`

     // I can not use $(this).html() or $(this).text() which will only return the `xx`.
  }
});
4

5 回答 5

2

其他答案不正确。这正是你得到它的方式。

$('a.xx,a.yy').each(function(index, currentLink){
   var z = currentLink.outerHTML;   //z will be <
});

另一种解决方案,使用 jQuery 获取锚点 HTML:

$('a.xx,a.yy').each(function(index, currentLink){
   alert($(currentLink.outerHTML).wrap('<p/>').parent().html());
});

这是 jsfiddle http://jsfiddle.net/wabjw/

于 2013-06-07T06:33:41.090 回答
1

这个对吗?

JS:

$("#t a").each(function(){
  if($(this).is(".xx,.yy")){
    console.log(this.outerHTML);
  }
});

它返回:"<a class=\"xx\">xx</a>"&"<a class=\"yy\">yy</a>"在控制台中。

于 2013-06-07T07:02:37.113 回答
1
$("#t a.xx,#t a.yy").each(function(){
    $('<div>').append($(this).clone()).html();
});
于 2013-06-07T06:26:52.703 回答
1
var html = '';
$('#t a.xx, #t a.zz').each(function(){
  html += $(this).wrap('<p/>').parent().html();
  $(this).unwrap();
});

JS 小提琴:http: //jsfiddle.net/rwGsR/9/

于 2013-06-07T06:51:34.097 回答
0

你可以试试 .find()

$("#t").find('.xx,.yy')
于 2013-06-07T06:41:46.357 回答