【问题标题】:jQuery search and replace not working (Wordpress)jQuery 搜索和替换不起作用(Wordpress)
【发布时间】:2016-06-19 04:45:24
【问题描述】:

我一定已经尝试了六种脚本(大部分都在这里找到,例如jQuery find and replace string)来替换我的 Wordpress 构建网站 (http://www.sehkelly.com/) 上的文本。

没有工作。我不够聪明,无法诊断原因(但还不够愚蠢,不知道如何运行脚本)。脚本以通常的方式进入 header.php,但没有结果。

例如,我主页上的所有“Shop”实例(在菜单、h2 元素、Wordpress 内容中)都保持原样,尽管有这个脚本...

$("span, p, div").each(function() {
    var text = $(this).text();
    text = text.replace("Shop", "Sale");
    $(this).text(text);
});

有什么想法吗?

我禁用缓存插件无济于事。

提前致谢。

更新

我完全有...

<script type="text/javascript">
    $(document).ready(function(){
        $("span, p, div").each(function() {
        var text = $(this).text();
        text = text.replace("type", "typo");
        $(this).text(text);
    });
</script>

还是不开心。

【问题讨论】:

  • 尝试打印控制台中的值。只需检查天气您在控制台中获取的值。document.ready 中的脚本在哪里?
  • 您是否在文档中调用了该脚本准备就绪$(function() { ... });
  • text = text.replace(new RegExp("Shop",'g'), "Sale");

标签: javascript jquery wordpress search replace


【解决方案1】:

如果你在你的网站上执行这样的代码,它会在你的 html 中造成混乱......不要那样做 :)

改为这样做:

$("span, p, div").each(function() {
    var text = $(this).html();
    text = text.replace("Shop", "Sale");
    $(this).html(text);
});

【讨论】:

    【解决方案2】:

    您需要在准备好的文档中调用它并使用正则表达式替换所有实例:

    $(function(){
        $("span, p, div").each(function() {
            var text = $(this).text();
            text = text.replace(/Shop/g, "Sale"); // regex instead of string
            $(this).text(text);
        });
    });
    

    【讨论】:

      【解决方案3】:

      使用此代码,然后您会很高兴

      <script type="text/javascript">
          $(document).ready(function(){
          var replaced = $("body").html().replace('Shop','Sale');
          $("body").html(replaced);
          });
      </script>
      

      【讨论】:

      • 就是这个。谢谢。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-06-12
      • 2013-08-28
      • 1970-01-01
      • 2019-02-04
      • 1970-01-01
      • 2014-10-10
      相关资源
      最近更新 更多