当replaceWith完成加载时运行javascript函数

时间:2014-12-04 17:04:19

标签: javascript jquery

我有jQuery replaceWith调用,而我只想在replaceWith完成加载时弹出警告

为实现这一点,我有一个非常天真的JavaScript实现:

$(document).ready(function (){
  $("#myDiv").click(function () {
    
    $("#myDiv").replaceWith("<div>Hello World!!!</div>");
    
    alert("done");
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv">Hello!</div>

问题是,在这种情况下,警报将独立于replaceWith所花费的时间弹出。如果速度很快,没问题,但如果replaceWith加载需要几秒钟(这是真实的情况),那么弹出窗口就会出现,我想避免这种情况。

我如何实现我正在寻找的行为?

3 个答案:

答案 0 :(得分:6)

尝试

$(document).ready(function() {
  var body = $("body");
  $("#myDiv").click(function(e) {
    var html =  $("<div>Hello World!!!</div>");
    $("#myDiv").replaceWith(html)
      .promise().done(function(elem) {
        if (body.find(html).is("*") 
            && !body.find(elem).is("*")) {
               alert("done");
        }
      });    
  });
});

$(document).ready(function() {
  var body = $("body");
  $("#myDiv").click(function(e) {
    var html = $("<img src=http://lorempixel.com/output/cats-q-c-1920-1920-2.jpg />");
        
        // $("<div>Hello World!!!</div>"); 

       
    $("#myDiv").replaceWith(html)
      .promise().done(function(elem) {
        if (body.find(html).is("*") 
            && !body.find(elem).is("*")) {
               alert("done");
        }
      });

  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="myDiv">Hello!</div>

答案 1 :(得分:0)

我会尝试获取您要更换的内容的价值 - 然后在更换后检查它是否存在 - 然后您可以提醒它完整。

小提琴: http://jsfiddle.net/eavxkc3f/

jquery的:

$(document).ready(function (){
  $(".myDiv").click(function () {

      var currentItem = $(".myDiv").html();
      var replacer = "<div>Hello World!!!</div>";

      $(".myDiv").replaceWith("<div>Hello World!!!</div>");

      if($(".myDiv").html != currentItem){
          alert("Done.");
      }

  });
});

答案 2 :(得分:0)

看看DOM MutationObserver规范,我认为它可以满足您的需求。在目标节点上注册它,它将监视该目标下的更改。

这是现已弃用的Mutation events

的更新版本

A blog post with additional good info(我在这里找到了此示例代码)

this fiddle中的工作示例(下面的代码)

$(document).ready(function (){
  $("#myDiv").click(function () {
    $("#myDiv").replaceWith("<div>Hello World!!!</div>");
  });
});

// select the target node
var target = document.querySelector('#divParent');

// create an observer instance
var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    //console.log(mutation.type);
      alert('Done');
  });
});

// configuration of the observer:
var config = { attributes: true, childList: true, characterData: true };

// pass in the target node, as well as the observer options
observer.observe(target, config);

// later, you can stop observing
//observer.disconnect();
相关问题