javascript 当 div 中的内部 html 更改时触发事件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17908002/
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-10-27 10:04:05  来源:igfitidea点击:

Fire event when inner html in div changed

javascriptjqueryhtml

提问by s0vet

I have divfor some informations, which are filled into with .innerHTMLby clicking on the button. The goal is I want to .slideDownthe div when the text in div is added. Is it possible to do it with jQuery ?

我有div一些信息,.innerHTML通过点击按钮填写。目标是.slideDown当添加 div 中的文本时我想要div。是否可以用 jQuery 做到这一点?

Example:

例子:

<div id="calcInfo"></div>

Adding text into div -

将文本添加到 div -

document.getElementById("calcInfo").innerHTML = 'someText';

I want to use this function after it :)

我想在它之后使用这个功能:)

if ($('#calcInfo').text().trim().length > 0) {
   $('#calcInfo').slideDown('slow', function() {});
};

I was trying .change()function, but it only works for inputand textareaelements. Many thanks for answer !

我正在尝试.change()函数,但它仅适用于inputtextarea元素。非常感谢您的回答!

Ondrej

翁德雷

回答by Khanh TO

You can do it by extending the $.html function. Like this:

您可以通过扩展 $.html 函数来实现。像这样:

(function($)
{
    var oldHtml = $.fn.html;
    $.fn.html = function()
    {
        var ret = oldHtml.apply(this, arguments);

        //trigger your event.
        this.trigger("change");

        return ret;
    };
})(jQuery);

Attach event handler:

附加事件处理程序:

$("#calcInfo").on("change",function(){
     if ($(this).text().trim().length > 0) {
        $(this).slideDown('slow', function() {});
     };
});

When you need to change your html. Do it like this:

当您需要更改 html 时。像这样做:

$("#calcInfo").html('someText');