2012-11-26 48 views
3

我想遍歷一個動態生成的頁面,抓取特定的跨度ID然後將該href內的該id附加到前一跨度。目前,這會在每個h2.classA中生成兩個鏈接,而不是每個實例中的相應單個鏈接。我應該將each()分配給h2嗎?任何幫助是極大的讚賞。抓取跨度id並將其追加到之前的跨度作爲href

現有的HTML

<h2> 
    <span class="classA"> </span> 
    <span class="classB" id="somename"> SomeName </span> 
    </h2> 

    <h2> 
    <span class="classA"> </span> 
    <span class="classB" id="anothername"> SomeName </span> 
    </h2> 

嘗試:

$("h2 span.classB").each(function() { 
    var content = $(this).attr('id'); 

    $('h2 span.classA').append('<a href="index.php?title='+content+'"> edit me </a>');    
    }); 

所需的HTML結果

<h2> 
    <span class="classA"><a href="index.php?title='+somename+'"> LINK1 </a></span> 
    <span class="classB" id="somename"> SomeName </span> 
    </h2> 

    <h2> 
    <span class="classA"><a href="index.php?title='+anothername+'"> LINK2 </a></span> 
    <span class="classB" id="anothername"> AnotherName </span> 
    </h2> 
+1

' $(本).prev( 'CLASSA')' – adeneo

回答

1

要附加的錨都在每次迭代classA元素,選擇前span元素,你可以使用prev方法:

$("h2 span.classB").each(function() { 
    $(this).prev().append('<a href="index.php?title='+this.id+'"> edit me</a>');    
}); 

http://jsfiddle.net/c7V9z/

1

更換

$('h2 span.classA').append('<a href="index.php?title='+content+'"> edit me </a>');    

$(this).prev('.classA').append('<a href="index.php?title='+content+'"> edit me </a>');