问题
Is there any way in jQuery to attach a listener to a <td>
cell so that when the text inside the cell has changed (by JavaScript, not the user), the event is triggered?
回答1:
To extend mway's answer, here is some code.
var td = $('#my-table tr td:eq(1)');
var tdHtml = td.html();
setInterval(function() {
if (td.html() !== tdHtml) {
// it has changed
tdHtml = td.html();
}
}, 500);
... and for his second suggestion.
function updateTd(html) {
$('#my-table tr td:eq(1)').html(html);
// additional code
}
You could also bind the DOMSubtreeModified
event to the element, but browser support isn't the best.
回答2:
Not natively, no. You have a couple options:
1) Use setInterval()
to test the value against its previous value, and act accordingly if it is different.
2) Use a common method for changing the cell contents, such that you can also perform additional logic when its value is changed without rewriting it numerous times.
回答3:
Horrors. May have been acceptable in 2010.
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
// NB the 1st char put or typed into a TD causes a mutation in the TD...
// but chars 2 ... n cause a mutation in its child '#text' node
let target = mutation.target;
if( target.cellIndex === undefined ){
target = target.parentElement;
}
// NB don't use a "truthy" test for cellIndex here: you would miss index 0!
if( target !== null && target.cellIndex !== undefined ){
// ... then the target is the TD where the content has changed.
}
});
});
const config = { attributes: true, childList: true, characterData : true, subtree : true };
observer.observe( htmlTable, config );
回答4:
Use input event listener.
$(document).on( 'input', '#table > tbody > tr > td',function(){ })
来源:https://stackoverflow.com/questions/3887976/jquery-event-listener-for-when-text-has-changed-in-a-td-cell