开发者

find and replace text , word translation

I have some problems with finding and replacing words in PHP files, especially when there is tons of them. So I thought that I will try to use javascript / jQuery. I'd like to create table witch word_to_replace@new_word to do so. This is my code which doesn't work (and runs very long), filter doesn't seem to work, any advices?

 (function($){
    var arr = [ 'photo-board.pl przyjazny portal fotograficzny@ ','Upload images from your@Up开发者_运维百科load zdjęć z ',
      'Total number of images@ Całkowita liczba zdjęć'];
    for(var i in arr)
    {
       var st_to_replace = arr[i].split('@')[0];
      // alert(st_to_replace);
      $('*').filter(function() {
        return $(this).text() == st_to_replace;
        }).html(arr[i].split('@')[1]);
    }
    }) (jQuery)


You're getting the text() of every page element (which will include the text of child elements) and replacing within it. That means, when you get the 'body' element you replace all the text, and then you get all the elements within body, and replace all the text, etc.

Something like this may work better:

(function($){
  var arr = [ 'photo-board.pl przyjazny portal fotograficzny@ ','Upload images from your@Upload zdjęć z ',
  'Total number of images@ Całkowita liczba zdjęć'];
  var bodyText = $('body').html();
  $.each(arr, function(i, v) {
    var words = v.split('@');
    var fromTxt = words[0], toTxt = words[1];
    bodyText = bodyText.replace(fromTxt, toTxt);
  });
  $('body').html(bodyText);
})(jQuery);

Demo here.

It's worth noting though that since this destroys and recreates the entire body content, you'll loose event handlers and data set using .data(...).


One of the performance issues of your script is the immediate call to .html every iteration of the filter. This is causing the browser to repaint the element every iteration.

You might consider editing the html detached from the dom and then, after the for and the filter loops, replacing the html in the dom.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜