此jQuery代碼段用指定的字符串替換網頁上的所有文本。 可用於基於變量的動態更改公司名稱或其他文本。 請記住,.replace()
>返回一個新字符串;您必須將其重新分配到元素以更新頁面。
這是使用它的方法:
>// Replace all periods (.) on the page with hyphens (-) var replace_str = $('body').html().replace(/./g,'-'); $('body').html(replace_str); // Alternative method if the above doesn't work var strNewString = $('body').html().replace(/./g,'---'); $('body').html(strNewString);
常見問題(常見問題解答):jQuery string替換
>Q1:如何使用jQuery替換HTML內容中的字符串? 使用
>和JavaScript的有效地替換HTML中的字符串。 選擇元素,使用.html()
>進行html,應用replace()
,然後使用結果更新元素的html。
.html()
replace()
$("p").html(function(index, oldHtml) { return oldHtml.replace("old string", "new string"); });是,但是
>僅替換第一個
出現。在所有情況下,使用“ g”標誌(全局)的正則表達式:
replace()
Q3:如何靶向HTML的特定部分?
使用更精確的jQuery選擇器。 例如,用“ myclass”類替換段落中的字符串:
$("p").html(function(index, oldHtml) { var regex = new RegExp("old string", "g"); return oldHtml.replace(regex, "new string"); });
Q4:我可以在屬性值中替換字符串嗎? 是的,使用
>方法:
$(".myClass").html(function(index, oldHtml) { var regex = new RegExp("old string", "g"); return oldHtml.replace(regex, "new string"); });
> Q5:我可以用html content替換字符串嗎? 是。 該方法接受HTML作為替代:以下示例用HTML內容替換“舊字符串”。 請注意,這在功能上等同於上面的示例,因為“新字符串”可以是html。
以上是jQuery替換頁面上的所有文本的詳細內容。更多資訊請關注PHP中文網其他相關文章!