jquery - 在 jquery 中的动态控件上应用 css

标签 jquery css

如何将 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/

相关文章:

javascript - 将 JSON 对象的字段转换为标题大小写

html - 为什么我的 2 列纯 CSS 布局不起作用?

html - 调整CSS下拉菜单的位置

jQueryUI 工具提示 : Issues with IE select boxes

javascript - 检测窗口滚动时到达容器底部

jQuery - 如何找到具有特定 id 的元素?

css - Bootstrap 3 : Column push after pull

html - 无法将 div 置于另一个 Bootstrap 之上

javascript - 移除 child 时动画 parent

javascript - 在 JQuery 的 .click() 事件中选择一个变量