問題があります。AJAX スクリプトによって時々更新されるテーブルがあります。この更新は、変更したくない Chrome プラグインから呼び出されます。そこで、テーブル セルの変更時に独自の関数を呼び出す、ある種の jQuery トリガーを追加したいと思います。
出来ますか?イベントonChangeを試しましたが、うまくいきません(私が正しければ入力用です)
前もって感謝します!
setInterval() を使用すると、テーブルのコンテンツを常に監視し、以前のコンテンツと比較できます。内容が異なる場合は、表が変更されています。
$(function() {
var previous = $("#mytable").text();
$check = function() {
if ($("#mytable").text() != previous) {
myOwnFunction();
}
previous = $("#mytable").text();
}
setInterval(function() { $check(); }, 1000);
}
function myOwnFunction() {
alert("CHANGED");
}
onchange
のような入力で使用するように設計されているため<select>
、このコンテキストでは機能しません。(などDOMSubtreeModified
)使用できる特定の dom 関連のイベントがありますが、これらはクロスブラウザーではなく、さまざまな実装があります(現在は廃止されている可能性があります)。
http://en.wikipedia.org/wiki/DOM_events
MutationEvents
上記のように、MutationObservers
私がまだ自分で使用していないものに置き換えられたようです...しかし、それはあなたが必要とすることをするように聞こえます:
http://dvcs.w3.org/hg/domcore/raw-file/tip/Overview.html#mutation-observers
それ以外はsetInterval
、ターゲット要素内の HTML の変更をリッスンするハンドラーにフォールバックできます...変更されたときに関数を起動します。
function watch( targetElement, triggerFunction ){
/// store the original html to compare with later
var html = targetElement.innerHTML;
/// start our constant checking function
setInterval(function(){
/// compare the previous html with the current
if ( html != targetElement.innerHTML ) {
/// trigger our function when a change occurs
triggerFunction();
/// update html so that this doesn't keep triggering
html = targetElement.innerHTML;
}
},500);
}
function whenChangeHappens(){
alert('this will trigger when the html changes in my_target');
}
watch( document.getElementById('my_target'), whenChangeHappens );
上記を jQueryify して任意の要素に適用できるようにしたい場合は、簡単に変更できます。
/// set up the very simple jQuery plugin
(function($){
$.fn.domChange = function( whenChanged ){
/// we want to store our setInterval statically so that we
/// only use one for all the listeners we might create in a page
var _static = $.fn.domChange;
_static.calls = [];
_static.iid = setInterval( function(){
var i = _static.calls.length;
while ( i-- ) {
if ( _static.calls[i] ) {
_static.calls[i]();
}
}
}, 500 );
/// step each element in the jQuery collection and apply a
/// logic block that checks for the change in html
this.each (function(){
var target = $(this), html = target.html();
/// by adding the function to a list we can easily switch
/// in extra checks to the main setInterval function
_static.calls.push (function(){
if ( html != target.html() ) {
html = target.html();
whenChanged();
}
});
});
}
})(typeof jQuery != undefined && jQuery);
/// example code to test this
(function($){
$(function(){
$('div').domChange( function(){
alert('I was changed!');
} );
});
})(typeof jQuery != undefined && jQuery);
明らかに、上記は非常に単純なバージョンであり、リスナーの追加と削除を処理するように拡張する必要があります。