jQuery event listener for when text has changed in a <td> cell?
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 开发者_如何学JAVAJavaScript, not the user), the event is triggered?
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.
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.
Use input event listener.
$(document).on( 'input', '#table > tbody > tr > td',function(){ })
Horrors. May have been acceptable in 2010.
const observer = new MutationObserver((mutations) => {
mutations.forEach((mutation) => {
let target = mutation.target;
// when the cell is empty, typing a character involves 1 event:
// target: TD, type childList, addNodes has 1 element
if( target.constructor.name === 'HTMLTableCellElement' && mutation.type === 'childList' ){
if( mutation.addedNodes.length == 1 ){
if( mutation.addedNodes[ 0 ].constructor.name === 'Text' ){
if( mutation.addedNodes[ 0 ].length == 1 ){
console.log( `new 1-char Text added, contents: |${mutation.addedNodes[ 0 ].data}|`)
// remove "hanging" BR if applicable
// NB this BR gets added automatically when the Text node is removed on
// becoming empty. You don't want to remove the BR until new text starts
// to be added, because if you remove the BR immediately the cursor goes
// to a funny location in the cell
if( target.childNodes.length == 2 ){
if( target.childNodes[ 1 ].nodeName === 'BR' ){
target.removeChild( target.childNodes[ 1 ] )
}
}
}
}
}
}
else if( target.constructor.name === 'Text' && mutation.type === 'characterData' ){
console.log( `Text has changed, contents now: |${target.data}|`)
}
const cell = target.constructor.name === 'HTMLTableCellElement'? target : target.parentElement
// respond to the changed text:
// NB with the "characterData" mutation where cell is null (Text set to empty string), this is followed immediately
// by another "childList" mutation where the target is the cell...
if( cell !== null ){
console.log( `current cell contents |${cell.innerHTML}|`)
}
});
});
const config = { attributes: false, childList: true, characterData : true, subtree : true };
observer.observe( htmlTable, config );
精彩评论