jQuery change event for non-forms elements
I'm looking for some kind of change
event but for non-forms elements.
Problem:
I h开发者_如何学Goave atable
where tr
tags are changing dynamicly by another script. Tr
elements are changing from display:block
to display:none
or vice versa.
And I need something like this:
event will listing for change of any tr
in my table
(not matter to display none
or block
) and after any change the script will check if all tr
s are set as display:none
and if true then do something.
DOM changes like that do not trigger events. Your options are to either update the code that modifies the DOM to also send a custom event, or to poll for changes. The first option is simplest to implement and can look something like this:
// Add an event listener for change events
$(document).bind("modified", function() {
alert("Someone modified " + this);
});
// Modify a table and trigger an event for it
$("#yourTable").css("display", "block").trigger("modified");
The poll option will be slower and is not recommended. Minimal example:
setInterval(function() {
var $table = $("#yourTable");
if ($table.css("display")!="block") {
alert("The table changed!");
}
}, 500);
this will check your table every 500 milliseconds.
One possibility is to set a timer to do this. For instance:
jQuery(function($) {
var table = $("selector_for_your_table");
var timerHandle = setInterval(function() {
if (table.find("tr:visible").length == 0) {
// No rows in the table are visible, do something
}
}, 500);
});
That checks once every half-second, which may well be too often. It depends on the size of the table, etc. You'll also want to turn this checking off whenever you can to avoid unnecessary work. You can cancel it by calling cancelInterval(timerHandle);
.
I would create functions for hiding and showing tr elements, and implementing an event firing in it, like calling a tr_was_hidden() or tr_was_shown() function. This way you can handle all the show/hide events as they fire.
$.fn.showTR = function() {
return $(this).each(function() {
$(this).show();
tr_was_shown();
});
};
$.fn.hideTR = function() {
return $(this).each(function() {
$(this).hide();
tr_was_hidden();
});
};
As a workaround you could use a timer to check periodical whether some content has changed or whether all tr
elements are set to display:none
.
精彩评论