如何将 css 样式应用于动态创建的表格元素? tblResult 是我正在创建的动态表。
<script type="text/javascript">
$(document).ready(function () {
$('#tblResult tbody tr').on('mouseover', function () {
$(this).addClass('highlightRow');
});
});
.addClass 不能与 jquery 中的动态控件一起使用是真的吗?
假设如果我想给子元素添加类:
$('body').on('mouseover', '#tblResult tbody tr td #im', function () {
$(this).addClass('transition');
});
可以吗??
最佳答案
由于您的表格已动态添加到 DOM,因此所有事件都将无法用于此表格和元素,例如 <tr>
或 <td>
在里面。在这种情况下,您需要使用 event delegation :
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all children matching a selector, whether those children exist now or are added in the future.
$(document).ready(function () {
$('body').on('mouseover','#tblResult tbody tr',function() {
$(this).addClass('highlightRow');
});
});
所以基本上,事件委托(delegate)将帮助您附加 mouseover
这些新创建的事件<tr>
本例中的元素。
关于jquery - 在 jquery 中的动态控件上应用 css,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22754250/