jQuery html元素内容改变事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4534955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:25:10  来源:igfitidea点击:

html element content change event

jquery

提问by vinnitu

i need to known event of content change my div element, how can i do it with jquery?

我需要知道内容更改我的 div 元素的事件,我该如何使用 jquery 做到这一点?

<div id="mydiv">text before</div>

after some time

一段时间后

<div id="mydiv>other content</div>

i do such way

我这样做

$("#mydiv").change(function() { alert('yes'); });

by doesn't work

通过不起作用

    (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?
});

but i see logs in console!

但我在控制台看到日志!

回答by ?ime Vidas

You could trigger a custom event after you change the content of the element:

您可以在更改元素的内容后触发自定义事件:

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");

回答by Uku Loskit

"The change event is sent to an element when its value changes. 

This event is limited to <input> elements, <textarea> boxes and <select> elements. "

You cannot use the change event on divs.

您不能在 div 上使用更改事件。