当使用jQuery.html(' string')时是否会触发任何事件?

时间:2015-03-03 14:41:17

标签: jquery

我有一个页面包含非常多的ajax调用,它将内容附加到html。 我想在每次这样的活动之后保存页面的当前html。

在这种情况下是否有任何事件被解雇?可能是一些$(文件).ready()或模拟?

2 个答案:

答案 0 :(得分:3)

在支持旧突变事件的浏览器上,是的,引发了突变事件。但是,已经弃用了mutation observers的变异事件,它为通知提供了非事件回调机制,这种机制可以更有效率,因为它们只能发出一个带有许多堆叠变化的回调(而不是单个事件)每次改变)。他们除了IE10及以下版本之外还有supported in modern browsers。在IE9和IE10上,您可以使用一个库(填充(polyfill))突变观察者,使用IE9 / 10对旧突变事件的部分支持。

这是一个简单的变异观察者例子:



var ob = new MutationObserver(function() {
  snippet.log("Change detected");
});
ob.observe($("#container")[0], {
  childList: true,
  characterData: true,
  subtree: true
});
$("button").on("click", function() {
  $("#container").html("Updated " + new Date());
});

<div id="container">This is the container whose contents are changed.</div>
<button type="button">Click me</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
&#13;
&#13;
&#13;

答案 1 :(得分:1)

由于您通过ajax调用向html页面添加“stuff”,因此您可以使用.ajaxStop()而不是侦听DOM更改(突变事件)。

$( document ).ajaxStop(function() {
    var bodycontent=$( "body" ).html(); //contains the html after (all) ajax calls
});

你可以类似地使用.ajaxStart(),但是在ajax调用之前。