Javascript jQuery:替换链接内的文本?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12663500/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
jQuery: replace text inside link?
提问by matt
I have the following html structure:
我有以下 html 结构:
<div class="event tiny">
<a href="/whatever">Something</a>
</div>
And I want to replace the text
of this link with "Anything" …
我想text
用“任何东西”替换此链接的...
When doing this …
这样做时……
$('.event a').replaceWith("Anything");
$('.event a').replaceWith("Anything");
… the text is replaced but also the link is gone.
...文本被替换,但链接也消失了。
When doing this …?
这样做的时候……?
$('.event a').text().replaceWith("Anything");
$('.event a').text().replaceWith("Anything");
…?nothing happens.
…?没发生什么事。
回答by I Hate Lazy
Like this, if the new text is all the same.
像这样,如果新的文字都是一样的。
$('.event a').text("Anything");
jQuery loops over the a
elements, and replaces its content with the "Anything"
text.
jQuery 循环遍历a
元素,并用"Anything"
文本替换其内容。
回答by Mike Gledhill
These suggestions, for setting the inner text & URL link within a a href
didn't work for me (using JQuery v1.8.3)
这些建议,用于在 a 中设置内部文本和 URL 链接a href
对我不起作用(使用 JQuery v1.8.3)
Here's what did work though:
这是有效的方法:
HTML
HTML
<a id="hrefAnalysisName" ></a>
JavaScript
JavaScript
$("a#hrefAnalysisName").attr("href", "/SomePage/ShowAnalysisDetails.aspx");
$("a#hrefAnalysisName").text("Show analysis");
Hope this helps!
希望这可以帮助!
回答by VVV
You could also change the link by href
if it's related to the URL.
如果链接href
与 URL 相关,您也可以更改链接。
$('a[href="/whatever"]').text("Anything");
回答by Anton Baksheiev
You are able to get this result the next ways result will be the same:
你可以得到这个结果,接下来的结果将是相同的:
HTML
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
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>')