开发者

when a function's work is completed

开发者 https://www.devze.com 2023-03-30 03:34 出处:网络
I\'m using a jQuery plugin, it gets data from an url, fetches, calculates and writes some data in 开发者_Python百科a div.

I'm using a jQuery plugin, it gets data from an url, fetches, calculates and writes some data in 开发者_Python百科a div.

I want to copy this div contents to another div, when that functions do its work.

for example:

$("#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 that code, i didn't have new contents in #div2.


you need to have myfunction take a callback parameter which it executes once the request is done

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


You will simply need to put this line:

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

into the success callback of the ajax code implemented in myFunction, to ensure that the operation happens once the client has received the response and inserted it into the DOM.


Ajax callbacks (such as success) will be deprecated in jQuery 1.8. Instead, you can use jQuery's deferred object to run (or undo) an action that requires one more conditions before it is performed.

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

Creating Responsive Applications Using jQuery Deferred and Promises


If you're the one writing the plugin, you should either hard-code it into the AJAX callback function, or allow for a callback function to be passed in with the options.

If you have no control over the plugin, you'll have to constantly query your div to see if it has been 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

精彩评论

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