【问题标题】:jQuery - Find and replace text, after body was loadedjQuery - 加载正文后查找和替换文本
【发布时间】:2010-02-27 23:51:51
【问题描述】:

我从其他人那里得到了一些惊人的帮助,关于用 jquery 查找和替换文本。

下面的代码将找到单词:“主题:”并将其替换为“名称:”

$("*").each(function () { 
   if ($(this).children().length == 0) { 
      $(this).text($(this).text().replace('Subject:','Name:')); 
   } 
});

而且效果非常好。

我遇到的唯一问题是替换页面加载后加载的文本。

我确实有一些 javascript 函数显示来自服务器的数据,但仅在页面加载了所有元素之后。例如,用户从下拉菜单中选择一个值,该值启动一个事件以从数据库加载产品列表。

我像这样格式化其中一些产品:

史密斯奶奶苹果 价格:每磅 x.xx 营养成分....

我只想找到一个替换词“价格:”,并可能将其替换为“成本:”。

但正如我所提到的,该数据尚未加载。并且仅在用户从下拉菜单中选择“Granny Smith Apples”后显示。

这是我必须忍受的限制吗?

【问题讨论】:

    标签: jquery find replace


    【解决方案1】:

    您可以尝试将事件附加到 ajaxStop event 以及加载:

    function replaceText() {
        var jthis = $(this);
        $("*").each(function() { 
            if(jthis.children().length==0) { 
                jthis.text(jthis.text().replace('Subject:', 'Name:')); 
            } 
        });
    }
    $(document).ready(replaceText);
    $("html").ajaxStop(replaceText);
    

    【讨论】:

    • 在哪里添加这个 sn-p? functions.php,我的主题文件?抱歉这个菜鸟问题。
    【解决方案2】:

    像这样从$(document).ready() 回调调用你的函数

    $(document).ready(function() { replace_stuff(); } );
    

    【讨论】:

    • 我已经在这样做了,仍然不会影响页面加载后加载的数据。
    【解决方案3】:

    下面的功能对我来说非常适合:

    function replaceText(selector, text, newText, flags) {
      var matcher = new RegExp(text, flags);
      $(selector).each(function () {
        var $this = $(this);
        if (!$this.children().length)
           $this.text($this.text().replace(matcher, newText));
      });
    }
    

    这是一个用法示例:

    function replaceAllText() {
      replaceText('*', 'Subject:', 'Name:', 'igm');
    }
    
    $(document).ready(replaceAllText);
    $('html').ajaxStop(replaceAllText);
    

    【讨论】:

      猜你喜欢
      • 2021-10-25
      • 2020-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-04-14
      • 2011-03-05
      • 2011-05-26
      • 2011-08-20
      相关资源
      最近更新 更多