EDIT: Notez que si vous n'êtes pas préoccupé par le soutien IE6, vous pouvez utiliser le sélecteur de pseudo CSS :hover
pour changer l'arrière-plan. Cela devrait probablement être la première considération.
#newTable tr:hover {
background: #E1EBF4;
}
Compte tenu de votre code actuel, vous pouvez simplement utiliser votre $tr
référence à la table:
function addRecentData(data) {
$('#newTable tr:last').after('<tr><td class="name"></td><td class="id"></td></tr>');
var $tr = $('#newTable tr:last');
$tr.find('.name').html(data.Name);
$tr.find('.id').html(data.Id);
$tr.mouseover(function() {
$(this).css('backgroundColor','#E1EBF4');
// this.style.backgroundColor = '#E1EBF4'; // or you could do this
});
}
Une autre approche serait d'utiliser inserAfter()
au lieu de after()
et attribuer immédiatement la variable.
function addRecentData(data) {
var $tr = $('<tr><td class="name"></td><td class="id"></td></tr>')
.insertAfter('#newTable tr:last');
$tr.find('.name').html(data.Name);
$tr.find('.id').html(data.Id);
$tr.mouseover(function() {
$(this).css('backgroundColor','#E1EBF4');
// this.style.backgroundColor = '#E1EBF4'; // or you could do this
});
}
Ou si chaque <tr>
doit obtenir le mouseover, vous pouvez utiliser .delegate()
sur la #newTable
pour prendre soin de la mouseover.
$('#newTable').delegate('tr', 'mouseover', function() {
$(this).css('backgroundColor','#E1EBF4');
// this.style.backgroundColor = '#E1EBF4'; // or you could do this
});
Maintenant éléments <tr>
obtiendrez automatiquement la fonctionnalité que vous voulez quand ils sont ajoutés à la table.
$ (this) .css ('backgroundColor', '# E1EBF4'); n'a pas fonctionné trop bien pour moi. L'autre option a bien fonctionné. Merci! – MrM