[英]Find replace html using javascript
我讀過很多不同的文章,我不知道為什么這對我不起作用。 任何幫助將不勝感激。 我敢肯定這很簡單。
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<script type="text/javascript">
$("body").children().each(function() {
$(this).html($(this).html().replace(/®/g,"<sup>®</sup>"));
});
</script>
</head>
<body>
<div>HelloWorld®</div>
</body>
</html>
您必須在頁面准備就緒后等待,以便在$(document).ready(function(){....})
內添加函數,或將<script>...</script>
標記移動為<body>...</body>
最后一個元素<body>...</body>
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>Untitled Document</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> </head> <body> <div>HelloWorld®</div> <script type="text/javascript"> $("body").children().each(function() { $(this).html($(this).html().replace(/®/g,"<sup>®</sup>")); }); </script> </body> </html>
<!doctype html> <html> <head> <meta charset="UTF-8"> <title>Untitled Document</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script type="text/javascript"> $(document).ready(function(){ $("body").children().each(function() { $(this).html($(this).html().replace(/®/g,"<sup>®</sup>")); }); }); </script> </head> <body> <div>HelloWorld®</div> </body> </html>
我已經測試了您的代碼,並且對我有用。 在修改元素之前和之后,我將元素的內容輸出到控制台:
$("body").children().each(function() {
console.log($(this).html());
$(this).html($(this).html().replace(/®/g,"<sup>®</sup>"));
console.log($(this).html());
});
結果是:
HelloWorld®
HelloWorld<sup>®</sup>
在這里檢查:
https://jsfiddle.net/m6kLgpj7/
您得到不同的結果嗎? 您正在觀察的問題是什么?
老實說,我可能只是通過為其指定一個唯一的ID作為目標,而不是遍歷體內的每個元素。 但是,由於這是您詢問的方法,因此我將這樣做:
$(document).ready(function() { $("body").children().each(function(idx, elem) { var newHtml = $(elem).html().replace(/®/g, "<sup>®</sup>"); $(elem).html(newHtml); }); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <title>Untitled Document</title> <body> <div>HelloWorld®</div> </body>
另外,請注意我放置了腳本其余部分以確保文檔准備就緒的方法。 這樣可以確保腳本在DOM准備就緒之前不會操縱DOM。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.