用 jquery 替换锚文本
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1625865/
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
replace anchor text with jquery
提问by Michel
i want to replace the text of a html anchor:
我想替换 html 锚的文本:
<a href="index.html" id="link1">Click to go home</a>
now i want to replace the text 'click to go home'
现在我想替换文字“点击回家”
i've tried this:
我试过这个:
alert($("link1").children(":first").val());
alert($("link1").children(":first").text());
alert($("link1").children(":first").html());
but it all gives me null or an empty string
但这一切都给了我 null 或空字符串
回答by Larry Lustig
Try
尝试
$("#link1").text()
to access the text inside your element. The # indicates you're searching by id. You aren't looking for a child element, so you don't need children(). Instead you want to access the text inside the element your jQuery function returns.
访问元素内的文本。# 表示您正在按 id 搜索。您不是在寻找子元素,因此您不需要 children()。相反,您希望访问 jQuery 函数返回的元素内的文本。
回答by zombat
To reference an element by id, you need to use the #
qualifier.
要通过 id 引用元素,您需要使用#
限定符。
Try:
尝试:
alert($("#link1").text());
To replace it, you could use:
要替换它,您可以使用:
$("#link1").text('New text');
The .html()
function would work in this case too.
该.html()
功能也适用于这种情况。
回答by Pointy
$('#link1').text("Replacement text");
The .text()
method drops the text you pass it into the element content. Unlike using .html()
, .text()
implicitly ignores any embedded HTML markup, so if you need to embed some inline <span>
, <i>
, or whatever other similar elements, use .html()
instead.
该.text()
方法将您传递的文本放入元素内容中。与使用.html()
,.text()
含蓄地忽略任何嵌入HTML标记,因此,如果您需要将某些内联<span>
,<i>
或任何其它类似的元素,使用.html()
来代替。
回答by Muhammad Attiq
Try this, in case of id
试试这个,以防万一
$("#YourId").text('Your text');
OR this, in case of class
或者这个,在上课的情况下
$(".YourClassName").text('Your text');
回答by alpc
function liReplace(replacement) {
$(".dropit-submenu li").each(function() {
var t = $(this);
t.html(t.html().replace(replacement, "*" + replacement + "*"));
t.children(":first").html(t.children(":first").html().replace(replacement, "*" +` `replacement + "*"));
t.children(":first").html(t.children(":first").html().replace(replacement + " ", ""));
alert(t.children(":first").text());
});
}
- First code find a title replace
t.html(t.html()
- Second code a text replace
t.children(":first")
- 第一个代码找到一个标题替换
t.html(t.html()
- 第二个代码文本替换
t.children(":first")
Sample<a title="alpc" href="#">alpc</a>
样本<a title="alpc" href="#">alpc</a>