At the end of the function

I use the jQuery plugin, it gets data from url, selects, calculates and writes some data to div.

I want to copy the contents divto another divwhen these functions do their job.

eg:

$("#div1").myfunction(); // it gets and calculates data and adds to #div1 . it needs 2-3 seconds to be done
var contents = $("#div1").html(); // when myfunction() done, copy contents
$("#div2").html(contents);

when I ran this code, I did not have new content in #div2.

+5
source share
4 answers

you need to have myfunctionto accept the callback parameter that it will execute after the request is executed

function myfunction(cb)
    $.ajax({
        type: "get",
        url: "page.html",
        success: function(data){
            $("#div1").html(data);
            if(typeof cb === 'function') cb();
        }
    });
}

myfunction(function(){
    $("#div2").html($("#div1").html());
});
+5
source

You just need to put this line:

$("#div2").html($("#div1").html());

ajax, myFunction, , , DOM.

+2

Ajax (, success) jQuery 1.8. jQuery deferred ( ) , .

var successFunction = function() {
  var contents = $("#div1").html();
  var newElement = $("<div id=div2></div>").html(contents);
  $("body").append(newElement);
}

var failedFunction = function() {
  // reset element or undo last change
  window.alert("Update Failed");
}


$.when(
  $.ajax(countParams),
  doCalculate()
).then(
  successFunction(),
  failedFunction()
);

jQuery Deferred Promises

+1

, AJAX, .

If you do not have control over the plugin, you will need to constantly request yours divto find out if it is updated:

var oldHTML = $("#div1").html(),
    counter = 0;

$("#div1").myfunction();

copyHTML();

function copyHTML()
{
    var newHTML = $("#div1").html();

    // we don't want this function to run indefinitely
    if (++counter > 15) return;

    if (newHTML == oldHTML)
        setTimeout(copyHTML, 1000);
    else
        $("#div2").html(newHTML);
}
0
source

All Articles