[英]Run javascript function when replaceWith finishes loading
我有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
需要幾秒鍾的時間加載(這是真實情況),那么彈出窗口就會出現在前面,我想避免這種情況。
如何實現我想要的行為?
嘗試
$(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-qc-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>
我會嘗試獲取您要替換的內容的值-然后在替換后檢查它是否存在-然后您可以提醒其完成情況。
小提琴: 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.");
}
});
});
看一下DOM MutationObserver規范,我認為它可以滿足您的要求。 在目標節點上注冊它,它將監視該目標下的更改。
這是現已棄用的Mutation事件的更新版本
博客文章,其中包含其他良好的信息 (以及在其中找到此示例代碼的地方)
這個小提琴中的工作示例(下面的代碼)
$(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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.