2013-11-29 35 views
-1

例子:Javascript或jQuery来替换文本中的标签

<a href=''>Hello</a> 

我想在所有A变量来替换字符串“Hello”到“不良好”使用jQuery或Javascript。

的结果是这样的:

<a href=''>Not Good</a> 

我怎么能这样做?

+2

$('a').text('Not Good');很好去 –

回答

1

我想要替换字符串 “Hello”,在所有A标记为'不好'

假设“你好”是不是a元素的唯一内容,但它仅包含文本:

$("a").text(function(_, text) { 
    return text.replace('Hello', 'Not Good'); 
}); 

如果存在的“你好”多次出现在同一a元素,使用正则表达式(/Hello/g)而不是简单的字符串。

参考:$.fn.textString#replace

0

请尝试一下。

$('a').text('Not Good'); 

试试这个LINK

1

使用.text()。你可以这样做:

$("a").html("Not Good"); 
//or 
$("a").text("Not Good"); 
1

试试这个,

$("a").text("Not Good"); 
1

尝试:

$("a").each(function(){ 
    if($(this).text() == "Hello"){ 
     $(this).text("Not Good"); 
    } 
}); 

DEMO here.

0

您可以为该链接指定一个id,然后更改其文本。它将避免替换其他超链接的文本。

<a id="hello" href=''>Hello</a> 
    $("#hello").html("Not Good"); 
      or 
    $("#hello").text("Not Good");