2012-09-30 72 views
7

我有以下HTML結構:jQuery:替換鏈接內的文本?

<div class="event tiny"> 
    <a href="/whatever">Something</a> 
</div> 

而且我想,以取代 「任何東西」 這個環節的text ...

做這件事時...

$('.event a').replaceWith("Anything");

...的文本被替換,但鏈接也消失了。

做這件事時...

$('.event a').text().replaceWith("Anything");

...沒有任何反應。

回答

19

像這樣,如果新文本都是一樣的。

$('.event a').text("Anything"); 

jQuery的循環通過a元素,並取代其與"Anything"文本內容。

0

如果URL與URL有關,也可以通過href更改鏈接。

$('a[href="/whatever"]').text("Anything"); 
0

你能夠得到這樣的結果下一個方法的結果將是相同的:

HTML

<div class="event tiny"> 
    <a class="html" href="/whatever">Something</a></br> 
    <a class="text" href="/whatever">Something</a></br> 
    <a class="replaceWith" href="/whatever">Something</a> 
</div> 

JS

$('.event a.html').html('Anything-html') 
$('.event a.text').text('Anything-text') 
$('.event a.replaceWith').replaceWith('<a class="replaceWith" href="/whatever">Anything-replaceWith</a>') 
4

這些建議,用於設置a href內的內部文本& URL鏈接,我沒有工作(使用JQuery v1.8.3)

這裏就是沒有工作,但:

HTML

<a id="hrefAnalysisName" ></a> 

的JavaScript

$("a#hrefAnalysisName").attr("href", "/SomePage/ShowAnalysisDetails.aspx"); 
$("a#hrefAnalysisName").text("Show analysis"); 

希望這有助於!