2013-11-29 34 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");