您的位置:首页 > Web前端 > JQuery

jquery监听div等元素的内容变化

2018-03-07 10:16 543 查看
方法一:change事件

change事件,在元素的值发生改变时触发,适用于文本域、textarea、select 。 或调用change()方法时可以监听。所以,我们可以模拟change为非表单元素监听change()事件。

<!Doctype>
<html>
<head>
<meta charset="utf-8">
<title>change事件</title>
<style>
#container {
min-height: 120px;
border: 1px solid #aaa;
}
</style>
</head>
<body>
<div id="container">

</div>
<button type="button" id="btn">add "aaa" for div</button>

<script src="jquery-1.11.3.js"></script>
<script>

function changes(){
alert("changes");
}

$("#btn").click(function() {
$("#container").append("aaa").change();
});
$("#container").bind("change", changes);
</script>
</body>
</html>

以上demo中,点击按钮,为div中动态添加内容,添加内容后,手动调用change()方法,为div模拟出change事件。

注: 1.以上demo中是追加的内容,所以没有判断div的内容是否发生变化,如果在其他场景下,可以自己判断div内容是否发生了变化

        2 .只要兼容jquery的浏览器都可以兼容此方法。

方法二:DOMNodeInserted事件

经测试,这个DOMNodeInserted事件可以监听到非表单元素的内容的变化,只有在插入节点时有效,相反DOMNodeRemoved事件,只有在移除节点时有效。DOMNodeInserted事件是js提供的一个dom2级事件(具体什么意思,我还没有弄懂,弄懂后回来补充,此处省略1000字。。。),总之,是可以监听到的。

<!Doctype>
<html>
<head>
<meta charset="utf-8">
<title>change事件</title>
<style>
#container {
min-height: 120px;
border: 1px solid #aaa;
}
</style>
</head>
<body>
<div id="container">

</div>
<button type="button" id="btn">add "aaa" for div</button>

<script src="jquery-1.11.3.js"></script>
<script>

function changes(){
alert("changes");
}

$("#btn").click(function() {
$("#container").append("aaa");
});
$("#container").bind("DOMNodeInserted", changes);
</script>
</body>
</html>


注: 此方法存在ie8及以下浏览器中失效

方法三:定时任务

可以通过定时任务来监听非表单元素的内容变化,如果以上两种方法均不适用的情况下,可以尝试此种方法

<!Doctype>
<html>
<head>
<meta charset="utf-8">
<title>change事件</title>
<style>
#container {
min-height: 120px;
border: 1px solid #aaa;
}
</style>
</head>
<body>
<div id="container">

</div>
<button type="button" id="btn">add "aaa" for div</button>

<script src="jquery-1.11.3.js"></script>
<script>

function changes(){
alert("changes");
}

$("#btn").click(function() {
$("#container").append("aaa");
});

var div = $("#container").html();
setInterval(function() {
var divNew = $("#container").html();
if(div != divNew) {
changes();
div = divNew;
}
}, 100);
</script>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: