用jQuery替换锚文本


86

我想替换HTML锚文本:

<a href="index.html" id="link1">Click to go home</a>

现在我要替换文本“点击回家”

我已经试过了:

alert($("link1").children(":first").val());
alert($("link1").children(":first").text());
alert($("link1").children(":first").html());

但这一切都给了我null或空字符串

Answers:


141

尝试

$("#link1").text()

访问元素内的文本。#表示您正在按ID搜索。您不需要的是子元素,因此不需要children()。相反,您想访问jQuery函数返回的元素内的文本。


1
谢谢。感到欣慰的是,我已经得到了答案,而且非常愚蠢……尝试了所有不同的陈述,却忘记了#号……。–
Michel Michel

62

要通过id引用元素,您需要使用#限定符。

尝试:

alert($("#link1").text());

要替换它,您可以使用:

$("#link1").text('New text');

.html()功能在这种情况下也将起作用。


18
$('#link1').text("Replacement text");

.text()方法将传递给您的文本放入元素内容中。与使用.html().text()含蓄地忽略任何嵌入HTML标记,因此,如果您需要将某些内联<span><i>或任何其它类似的元素,使用.html()来代替。



-1
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());
    });
}
  • 第一个代码找到标题替换 t.html(t.html()
  • 第二个代码一个文本替换 t.children(":first")

样品 <a title="alpc" href="#">alpc</a>


1
尽管答案中的代码可能会起作用,但是您应该努力创建一个出色的答案,以解释其原因和工作方式。
伊恩·斯台普顿·科尔达斯科
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.