我需要知道内容更改我的div元素的事件,我怎么能用jquery做呢?
<div id="mydiv">text before</div>
一段时间后
<div id="mydiv>other content</div>
我这样做
$("#mydiv").change(function() { alert('yes'); });
by不起作用
(function(){
var interval;
jQuery.event.special.contentchange = {
setup: function(data, namespaces) {
var $this = $(this);
var $originalContent = $this.text();
interval = setInterval(function(){
if($originalContent != $this.text()) {
console.log('content changed');
$originalContent = $this.text();
jQuery.event.special.contentchange.handler();
}
},500);
},
teardown: function(namespaces){
clearInterval(interval);
},
handler: function(namespaces) {
jQuery.event.handle.apply(this, arguments)
}
};
})();
$("#mydiv").bind("contentchange", function() {
alert('yes'); ///no alert! why?
});
但我在控制台中看到日志!
答案 0 :(得分:12)
更改元素的内容后,您可以触发自定义事件:
var $mydiv = $("#mydiv");
// set up the custom event handler
$mydiv.bind("contentchange", function() {
alert("changed");
});
// change the content and trigger a custom event
$mydiv.html("other content").trigger("contentchange");
// and again
$mydiv.html("yet other content").trigger("contentchange");
答案 1 :(得分:1)
"The change event is sent to an element when its value changes.
This event is limited to <input> elements, <textarea> boxes and <select> elements. "
您无法在div上使用更改事件。