【问题标题】:Find replace html using javascript使用javascript查找替换html
【发布时间】:2016-10-21 15:50:44
【问题描述】:

我已经阅读了很多不同的帖子,但我不明白为什么这对我不起作用。任何帮助将不胜感激。我相信这很简单。

<!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>

【问题讨论】:

  • 你想达到什么目的?
  • 您正在使用 jQuery-isms(例如 $()),但您的页面似乎没有在 &lt;script&gt; 标记中加载 jQuery..
  • 问题解决后不要更新问题,使用解决问题的答案旁边的绿色复选标记。
  • 那是我的错,抱歉新来的。感谢您的反馈

标签: javascript replace find


【解决方案1】:

您必须在页面准备好后等待,以便将您的函数添加到 $(document).ready(function(){....}) 中或将您的 &lt;script&gt;...&lt;/script&gt; 标记作为最后一个元素移动到 &lt;body&gt;...&lt;/body&gt;

<!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>

【讨论】:

  • 您不能在此处放置&lt;script&gt; 标签。那是无效的 HTML。它需要在&lt;head&gt;&lt;body&gt; 标签内。
  • 我就是这么想的。我从未见过在 标记之外使用
  • 运行 sn -p 它的工作结果是HelloWorld&lt;sup&gt;®&lt;/sup&gt;
【解决方案2】:

我已经测试了您的代码,它适用于我。我在修改它们之前和之后将元素的内容输出到控制台:

$("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/

你得到不同的结果了吗?您观察到的问题是什么?

【讨论】:

    【解决方案3】:

    说实话,我可能只是通过给它一个唯一的 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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-02-02
      • 1970-01-01
      • 2016-04-14
      • 1970-01-01
      • 2016-02-08
      • 2013-03-15
      • 1970-01-01
      相关资源
      最近更新 更多