jQuery - Find and replace text, after body was loaded

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-17 15:43:02

问题


I received some amazing help from others, concerning finding and replacing text with jquery.

The code below will find the word: "Subject:" and replace it with "Name:"

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

And this works wonderfully.

The only thing I'm running into issues with is replacing text that is loaded after the page loads.

I do have some javascript functions that are displaying data from the server, but only after the page has loaded all elements. For example, a user selects a value from a dropdown that initiates an event to load a list of products from the database.

I format some of those products like this:

Granny Smith Apples Price: x.xx per pound Nutritional facts....

I will only want to find a replace the word "Price:", and possibly replace it with "Cost:".

But as I mentioned, that data has not been loaded yet. And only displays after the user selects "Granny Smith Apples" from the dropdown menu.

Is this a limit I have to live with?


回答1:


You could try attaching an event to the ajaxStop event as well as on load:

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);



回答2:


Call your function from the $(document).ready() callback like this

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



回答3:


The function below works perfectly for me:

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));
  });
}

Here's a usage example:

function replaceAllText() {
  replaceText('*', 'Subject:', 'Name:', 'igm');
}

$(document).ready(replaceAllText);
$('html').ajaxStop(replaceAllText);


来源:https://stackoverflow.com/questions/2349446/jquery-find-and-replace-text-after-body-was-loaded

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!