有什么办法观看,如果一个div内的内容改变?
假设我有:
<div id="hello"><p>Some content here</p></div>
其中在某点5秒后更改为:
<div id="hello"><ul><li>This is totally different!</li></ul></div>
如何通过回调或其他方式通知这一点?我可以在大多数情况下得到的javascript,这是插入,告诉我。但我想知道是否可能。
解决方法
jQuery .change()方法仅适用于表单字段。
我为你写了一个小jQuery插件:
<!-- jQuery is required --> <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> <!-- this is the plugin --> <script> jQuery.fn.contentChange = function(callback){ var elms = jQuery(this); elms.each( function(i){ var elm = jQuery(this); elm.data("lastContents",elm.html()); window.watchContentChange = window.watchContentChange ? window.watchContentChange : []; window.watchContentChange.push({"element": elm,"callback": callback}); } ) return elms; } setInterval(function(){ if(window.watchContentChange){ for( i in window.watchContentChange){ if(window.watchContentChange[i].element.data("lastContents") != window.watchContentChange[i].element.html()){ window.watchContentChange[i].callback.apply(window.watchContentChange[i].element); window.watchContentChange[i].element.data("lastContents",window.watchContentChange[i].element.html()) }; } } },500); </script> <!-- some divs to test it with --> <p>Testing it: (click on divs to change contents)</p> <div id="a" onclick="$(this).append('i')">Hi</div> <div id="b" onclick="$(this).append('o')">Ho</div> <div class="c" onclick="$(this).append('y')">He</div> <div class="c" onclick="$(this).append('w')">He</div> <div class="c" onclick="$(this).append('a')">He</div> <!-- this is how to actually use it --> <script> function showChange(){ var element = $(this); alert("it was '"+element.data("lastContents")+"' and now its '"+element.html()+"'"); } $('#a').contentChange(function(){ alert("Hi!") }); $('div#b').contentChange( showChange ); $('.c').contentChange(function(){ alert("He he he...") }); </script>
请注意,此监视仅更改元素(html)的内容,而不是属性。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。