繁体   English   中英

使用JavaScript查找替换HTML

[英]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> 
我认为,当您使用每种方法提供的jQuery的第二个参数(元素)时,而不是在整个地方都使用“ this”时,会更清楚……只是我个人的喜好。

另外,请注意我放置了脚本其余部分以确保文档准备就绪的方法。 这样可以确保脚本在DOM准备就绪之前不会操纵DOM。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM