DOM ノードのコンテンツがいつ変更されるかを知る必要があります。.text(val)
幸いなことに、これらすべての変更はorの呼び出しによって行われると確信できます.html(val)
。
これら2つの関数が呼び出されたときにjQueryにイベントを送信させることは可能ですか?
これを本当に達成する必要がある場合は、jQueryにモンキーパッチを適用することを検討できます。基本的な要点編集済み-参照リンクから取得:
(function($){
// store original reference to the method
var _old = $.fn.text;
$.fn.text = function(text){
// modifications go here
return _old.apply(this,arguments);
};
})(jQuery);
これはかなり手間がかかるので、必要なものを取得する唯一の方法である場合にのみ検討します。jQueryAPIの変更にはかなり注意する必要があります。
jQuery関数text()
とを拡張できhtml()
ます。私はこれをどこかで見つけました(ソースがないことを残念に思います、誰がそれのクレジットを持っているべきか知っているなら誰かが編集してください)そしてそれは私にとって魅力のように働きます
(function ($) {
var originalHtmlFunction = $.fn.html;
$.fn.html = function (value) {
if (typeof value != 'undefined') {
var jqObj = originalHtmlFunction.call(this, value);
// Do your magic here
return jqObj;
}
else {
return originalHtmlFunction.call(this, value);
}
};
var originalTextFunction = $.fn.text;
$.fn.text = function (value) {
if (typeof value != 'undefined') {
var jqObj = originalTextFunction.call(this, value);
// Do your magic here
return jqObj;
}
else {
return originalTextFunction.call(this,value);
}
};
})(jQuery);
.text()
そのように (または任意の jQuery メソッド)をオーバーロードし、変更されたものはすべて、作成できるログクラスに保存できます。以下は基本クラスです。
var textLogger = new (function textChangeLog () {
this.logArray = [];
this.add = function (item) {
this.logArray.push(item);
};
this.displayLog = function (index) {
if (typeof index === 'number') { console.log( this.logArray[index] ); }
else { console.log( this.logArray ); }
};
})();
ここで、現在のものを上書きし、.text()
いくつかの追加を追加します。ロギング クラス、およびコールバック関数 (より多くの機能が必要な場合 )
$.fn.oldText = $.fn.text;
// ** NOTE: At any point you can just use $('body').oldText('change it');
// to by pass any of the below changes / overrides to .text()
$.fn.text = function (str, funcEvent) {
try {
// Let's log anything that's being changed in our textLogger class Array
textLogger.add($(this));
// call the original .text()
$(this).oldText(str);
// the optional event you passed in
var callbackFunc = typeof funcEvent !== 'undefined' ? funcEvent : function () { };
callbackFunc();
}
catch(e) { console.log(e); }
};
次に、いくつかの使用例を実行してから、コンソールで結果を確認するためにtextLogger.displayLog()を実行します。jQueryセレクター/コンテキスト/ID全体が配列に表示されます。
$('div').text('here');
$('#anotherExample').text('we changed this too!');
textLogger.displayLog();
$('#cbTest').text('blah', function () { console.log('callback!'); });
編集jsFiddle を更新して、テキストが変更されたときにカスタム イベントをトリガー/応答する方法を示しました。
はい、可能ですが、上記の方法の使い方によっては効率的でない場合があります。
$.each(["text","html"], function(i,method) {
var oldMethod = $.fn[method];
$.fn[method] = function(){
this.trigger(method+"change");
oldMethod.apply(this,arguments);
};
});
// sample usage:
$("#someelement").on("textchange",function(){
alert("Text Change!");
}).text("Foobar");