2008-10-08 36 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>