0

问题很简单。我有一个庞大的 javascript 应用程序。在应用程序中有很多次我使用看起来像这样的代码 -

$('#treat').html(new_data);
....
....
$('#cool').html(some_html_data);
....
....
$('#not_cool').html(ajax_data);

所以我想做的是,每次调用这个 html() 函数时,我都想执行一组函数。

function do_these_things_every_time_data_is_loaded_into_a_div()   
{      
     $('select').customSelect();
     $('input').changeStyle();
     etc.
}

我该怎么做呢?谢谢你。

4

5 回答 5

2

您可以为此使用自定义事件处理程序:

$('#treat').html(new_data);

// Trigger the custom event after html change
$('#treat').trigger('custom');

// Custom event handler
$('#treat').on('custom', function( event) {
  // do_these_things_every_time_data_is_loaded_into_a_div
  alert('Html had changed!');
});

更新

根据此处的答案并进行一些修改,您可以执行以下操作:

// create a reference to the old `.html()` function
$.fn.htmlOriginal = $.fn.html;

// redefine the `.html()` function to accept a callback
$.fn.html = function (html, callback) {
    // run the old `.html()` function with the first parameter
    this.htmlOriginal(html);
    // run the callback (if it is defined)
    if (typeof callback == "function") {
        callback();
    }
}

$("#treat").html(new_data, function () {
    do_these_things_every_time_data_is_loaded_into_a_div();
});

$("#cool").html(new_data, function () {
    do_these_things_every_time_data_is_loaded_into_a_div();
});

根据您的要求,易于维护且代码更少。

于 2013-10-21T12:26:00.587 回答
1

您可以覆盖 jQuery.fn.html() 方法,如覆盖 jQuery 函数中所述

例如,使用这个:

var oHtml = jQuery.fn.html;
jQuery.fn.html = function(value) {
    if(typeof value !== "undefined")
    {
        jQuery('select').customSelect();
        jQuery('input').changeStyle();
    }
    // Now go back to jQuery's original html()
    return oHtml.apply(this, value);
};
于 2013-10-21T12:37:52.743 回答
0

可以用自己的函数替换html函数,然后调用函数html:

$.fn.html = (function(oldHtml) {
        var _oldHtml = oldHtml;

        return function(param) {
            // your code
            alert(param);
            return _oldHtml.apply(this, [param]);
        };
    })($.fn.html);
于 2013-10-21T12:39:05.327 回答
0

html()被调用时,它通常会使 DOM 对象发生变化,因此您可以寻找 DOM 更改事件处理程序,每当您的主页面的 HTML 更改时都会调用它。我发现

是否有 JavaScript/jQuery DOM 更改监听器?

如果这有助于您的事业。

于 2013-10-21T12:24:41.073 回答
0

我有一个小脚本给你。将其插入到您的 javascript 中:

//@Author Karl-André Gagnon
$.hook = function(){
    $.each(arguments, function(){
        var fn = this
        if(!$.fn['hooked'+fn]){
            $.fn['hooked'+fn] = $.fn[fn];
            $.fn[fn] = function(){
                var r = $.fn['hooked'+fn].apply(this, arguments);
                $(this).trigger(fn, arguments);
                return r
            }
        }
    })
}

这允许您“挂钩”jQuery 函数并在调用它时触发事件。

这里怎么用,你先绑定你要触发的函数。在您的情况下,它将是.html()

$.hook('html');

然后你添加一个事件监听器.on。如果没有动态添加的元素,您可以使用直接绑定,否则,委派事件可以工作:

$(document).on('html', '#threat, #cool, #not_cool',function(){
    alert('B');
})

该功能将在每次#threat, #cool or #not_cool调用时启动.html

$.hook插件不是全文本的,可能存在一些错误,但对于您的 HTML,它可以工作。

示例:http: //jsfiddle.net/5svVQ/

于 2013-10-21T12:44:09.880 回答