开发者

Using jQuery to change a string of HTML: wont update the string

I have some JQuery that takes 2 strings of HTML. Each string contains exactly the same html except in one string the innertext contents of each element will be different, this string is called newContent, the other oldContent.

My function: iterates over oldContent, for each element of the class "updatable"(inside oldContent) we change its innerText to the innerText of the same element in newContent.

My Problem: it is not changing the contents of oldContent, after I perform the function, oldContent contains the exact same HTML (where what should happen is that elements of the class updatable should have different innerText).

Why doesn't the string oldContent change?

    function insertContentIntoUpdatableElements( oldContent, newContent )
{
    // Pre: oldContent & newContent must be strings of HTML returned from jquery's
    //      $("").html()

    try
    {
        alert("BEFORE: "+oldContent);
        var index       = 0;
        var oldElements = $(oldContent).find(".updatable");
        var newElements = $(newContent).find(".updatable");

        $(oldContent).find(".updatable").e开发者_如何学JAVAach( function()
        {
            var txt = $(newElements[index]).text(); alert("TEXT: "+txt); 
            alert("OLD TEXT: "+$(this).text());
            $(this).text(txt);
            index++;

            alert("NEW TEXT: "+$(this).text());  // prints out CORRECT updated/changed text
        });

        alert("AFTER: "+oldContent);   // prints out INCORRECT updated/changed text for each element of class "updatable"
        return oldContent;
    }
    catch(ex) { alert("In insertContentIntoUpdatableElements(): "+ex); return "FAILED"; }
}


This should do the trick.

  function insertContentIntoUpdatableElements( oldContent, newContent )
  {
    var result = $(oldContent);
    var oldElements = result.find(".updatable");
    var newElements = $(newContent).find(".updatable");

    $(oldElements).each(function(index, el)
    {
      $(oldElements[index]).text($(newElements[index]).text());
    });
    return result;
  }

See a working Demo on jsFiddle: http://jsfiddle.net/ZZVgh/

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜