Javascript 如何在jquery中获取当前选定元素的outerHTML

Javascript 如何在jquery中获取当前选定元素的outerHTML,javascript,jquery,Javascript,Jquery,鉴于htmls: <div id="t"> <a class="xx">xx</a> <a class="yy">yy</a> <a class="zz">zz</a> </div> 我试过这个: $("#t a").each(function(){ if($(this).is(".xx,.yy"){ //here how to get the out the HTML

鉴于htmls:

<div id="t">
   <a class="xx">xx</a>
   <a class="yy">yy</a>
   <a class="zz">zz</a>
</div>
我试过这个:

$("#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`.
  }
});
$(“#ta”)。每个(函数(){
如果($(此).is(“.xx,.yy”){
//在这里,我想获得'a'元素的完整HTML
//也就是说,我想得到xx`
//我不能使用$(this).html()或$(this).text(),它们只返回'xx`。
}
});
$(“#ta.xx,#ta.yy”)。每个(函数(){
$('').append($(this.clone()).html();
});
$(“#ta.xx,#ta.yy”)。每个(函数(){
$('').append($(this.clone()).html();
});

其他答案都不正确。以下是您得到答案的确切方式

$('a.xx,a.yy').each(function(index, currentLink){
   var z = currentLink.outerHTML;   //z will be <
});
$('a.xx,a.yy')。每个(函数(索引,currentLink){
var z=currentLink.outerHTML;//z将是<
});
另一个解决方案是使用jQuery获取锚HTML:

$('a.xx,a.yy').each(function(index, currentLink){
   alert($(currentLink.outerHTML).wrap('<p/>').parent().html());
});
$('a.xx,a.yy')。每个(函数(索引,currentLink){
警报($(currentLink.outerHTML).wrap('

').parent().html()); });


这是jsfiddle

的答案,其他答案都不正确。下面是您得到它的确切方式

$('a.xx,a.yy').each(function(index, currentLink){
   var z = currentLink.outerHTML;   //z will be <
});
$('a.xx,a.yy')。每个(函数(索引,currentLink){
var z=currentLink.outerHTML;//z将是<
});
另一个解决方案是使用jQuery获取锚HTML:

$('a.xx,a.yy').each(function(index, currentLink){
   alert($(currentLink.outerHTML).wrap('<p/>').parent().html());
});
$('a.xx,a.yy')。每个(函数(索引,currentLink){
警报($(currentLink.outerHTML).wrap('

').parent().html()); });

这是您可以尝试的JSFIDLE

你可以试试。查找()

var html='';
$('#ta.xx,#ta.zz')。每个(函数(){
html+=$(this.wrap(“

”).parent().html(); $(this.unwrap(); });

JS Fiddle:

var html='';
$('#ta.xx,#ta.zz')。每个(函数(){
html+=$(this.wrap(“

”).parent().html(); $(this.unwrap(); });

JS Fiddle:

这是正确的吗

JS:

它在控制台中返回:
“xx”
“yy”

是否正确

JS:


它返回:
“xx”
&
“yy”
在console中。

我不是100%确定,但我更新了答案以包含一个jQuery解决方案,该解决方案应该可以工作,因为您似乎已经在使用jQuery。我不是100%确定,但我更新了答案以包含一个jQuery解决方案,该解决方案应该可以工作,因为您似乎已经在使用jQuery。检查我的更新答案检查我的更新答案
$("#t").find('.xx,.yy')
var html = '';
$('#t a.xx, #t a.zz').each(function(){
  html += $(this).wrap('<p/>').parent().html();
  $(this).unwrap();
});
$("#t a").each(function(){
  if($(this).is(".xx,.yy")){
    console.log(this.outerHTML);
  }
});