2012-03-01 64 views
0

我有以下結構如下。使用jQuery我需要獲取每個鏈接並在其下面顯示href。我可以使用一些子選擇編寫代碼爲每個但我只是想寫的東西,它會爲所有的div的「關口」類,並且將允許未來增加...通過div和顯示文本jQuery循環

<div class="col"> 
    <a href="http://google.com">Google</a> 
</div> 

<div class="col"> 
    <a href="http://yahoo.com">Yahoo!</a> 
</div> 

<div class="col"> 
    <a href="http://facebook.com">Facebook</a> 
</div> 

<div class="col"> 
    <a href="http://twitter.com">Twitter</a> 
</div> 

上述應變成...

<div class="col"> 
    <a href="http://google.com">Google</a> 
    <span>http://google.com</span> 
</div> 

<div class="col"> 
    <a href="http://yahoo.com">Yahoo!</a> 
    <span>http://yahoo.com</span> 
</div> 

<div class="col"> 
    <a href="http://facebook.com">Facebook</a> 
    <span>http://facebook.com</span> 
</div> 

<div class="col"> 
    <a href="http://twitter.com">Twitter</a> 
    <span>http://twitter.com</span> 
</div> 

任何幫助表示讚賞!

+0

甚至不知道從哪裏begin..If我店裏的.COL一個「HREF到一個變量,它會被每個被覆蓋..在一段時間內沒有做過這樣的事情 – stewart715 2012-03-01 18:48:57

回答

3

這意味你沒有嘗試過在所有寫代碼的。你應該真的能夠自己做到這一點。

$('.col a').each(function() { 
    var $this = $(this); 
    $("<span>"+$this.attr('href')+"</span>").insertAfter($this); 
}); 
0

這應該這樣做。你可以使用每個。閱讀更多關於選擇器。

$(document).ready(function(){ 
    $("div.col").each(function(){ 
     var hreftext = $(this).find("a").attr("href"); 
     $(this).append("<span>" + hreftext + "</span>"); 
    }); 

});

3
$('div.col').each(function(){ 
    alert($(this).find("a").attr("href")); 
    //figure out the rest yourself 
}); 
0

像這樣的工作:

$('div.col').each(function() { 
    var $a = $(this).find('a:first'), 
     href = $a.attr('href'); 
    $('<span>').text(href).insertAfter($a); 
}); 
2
$('.col > a').after(function() { 
    return $('<span>', {text:this.href}); 
}); 
+1

非常簡化的解決方案,我喜歡它。 – 2012-03-01 18:57:24

+0

**演示:** http://jsfiddle.net/HffG6/ – 2012-03-01 19:00:32

0
$(".col").each(function(){ 
var v= $(this).find("a");  
$("<span/>",{text:v.attr('href')}).insertAfter(v); 
}); 

DEMO

0

這可以用一個基本的jQuery的 '追加()' 來完成

JsFiddle Example

$('div.col').each(function(){ 
     var href = $(this).children('a:first').attr('href'); 
     $(this).append('<span>' + href + '</span>'); 
    }); 
-1

是的,我同意每個解決方案。但是如果你緩存你的選擇器會更好。 否則每次jQuery必須潛入DOM。 如果它的大名單可能會影響性能。

var col = $('.col a'); 
col.each(function(){ 
    var val = $(this).text(); 
    $(this).append("<span>"+val); 
})​ 

http://jsfiddle.net/cXkqc/2/

更新

有從我的一部分,解釋問題的錯誤。更新代碼&鏈接。

var col = $('.col a'); 
    col.each(function(){ 
    var val = $(this).attr('href'); 
    $(this).after("<span>"+val); 
})​ 

http://jsfiddle.net/cXkqc/3/

感謝@am不是我什麼

+0

*「否則每次jQuery都要潛入DOM ......」*這是不對的。如果您要重複使用'.col a'選項,情況就是如此。如果你只使用它一次,那麼jQuery將只做一個DOM選擇。 – 2012-03-01 19:29:40

+0

哦,對不起..那句話是一個錯誤。請閱讀 - 「但是如果你打算在其他地方使用它,最好是緩存你的選擇器。」謝謝 - @amnotiam – 2012-03-01 19:41:38

+0

負面標記:(? – 2012-03-02 03:30:56