2008-10-08 67 views
5

我已经有点HTML像这样:剔除链接jQuery中

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

我需要剥离,所以我刚离开一对夫妇的图像标签的链接。用jQuery做这件事最有效的方法是什么?

回答

8
$("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. 
    }); 
+0

如果有任何兄弟姐妹的形象,那么这将复制它们。你可能想用$(this).children(“img”)。remove()来代替。 – Sugendran 2008-10-09 02:51:25

+0

@Sugendran:是。 – Shog9 2008-10-09 03:32:49

4

这应做到:

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

在普通的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>