Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/86.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 剥离jQuery中的链接_Javascript_Jquery - Fatal编程技术网

Javascript 剥离jQuery中的链接

Javascript 剥离jQuery中的链接,javascript,jquery,Javascript,Jquery,我有点像这样的html: <a href="#somthing" id="a1"><img src="something" /></a> <a href="#somthing" id="a2"><img src="something" /></a> 我需要剥离链接,所以我只剩下几个图像标签。使用jQuery最有效的方法是什么?$(“a>img”).parent()//匹配所有,选择parents $("a > i

我有点像这样的html:

<a href="#somthing" id="a1"><img src="something" /></a>
<a href="#somthing" id="a2"><img src="something" /></a>

我需要剥离链接,所以我只剩下几个图像标签。使用jQuery最有效的方法是什么?

$(“a>img”).parent()//匹配所有,选择parents
$("a > img").parent()   // match all <a><img></a>, select <a> parents
   .each( function()    // for each link
   { 
      $(this).replaceWith(              // replace the <a>
         $(this).children().remove() ); // with its detached children.
   });
.each(函数()//用于每个链接 { $(this).replaceWith(//替换 $(this.children().remove());//及其分离的子对象。 });
这应该可以做到:

$('a[id^=a]').each(function() { $(this).replaceWith($(this).html()); });

在纯javascript中,它类似于:

<script type="text/javascript">
window.onload = function(){
  var l = document.getElementsByTagName("a");
  for(i=0, im=l.length; im>i; i++){
    if(l[i].firstChild.tagName == "img"){
      l[i].parentNode.replaceChild(l[i].firstChild,l[i]);
    }
  }
}
</script>

window.onload=函数(){
var l=document.getElementsByTagName(“a”);
对于(i=0,im=l.length;im>i;i++){
如果(l[i].firstChild.tagName==“img”){
l[i].parentNode.replaceChild(l[i].firstChild,l[i]);
}
}
}

如果图像有任何同级,则此操作也会复制它们。您可能想改用$(this.children(“img”).remove()。没有兄弟姐妹。但这是一个很好的观点。jQuery现在被用来优雅地替代您在这里提出的代码和平。无论如何谢谢你!说真的,这段代码只是展示了jQuery的优雅。这段代码和Shog9的代码完全相同,但其中一段更小,阅读起来更整洁。尽管如此,这段代码也能很好地完成这项工作!优雅地——是的,它看起来相当整洁,但在jQuery内部它要大得多,所以如果您没有其他理由使用一个巨大的库,请使用这个。但当然,defrex要求使用jQuery,但事实并非如此也许这对我来说不好,但我已经习惯了jquery(以及类似的库),我甚至无法想象再次尝试用原始js编写代码。我认为我的用户可以处理开销。