表上的jQuery toggleClass无法正常工作

时间:2013-06-28 20:09:46

标签: javascript jquery html-table hover

当鼠标悬停在表格行上时,我正在尝试突出显示表格行。所以我正在使用jQuery的toggleClass()函数。值得一提的是,表行最初不存在,它们是在对服务器的AJAX调用之后创建的,然后插入到表中。创建的表行具有class =“table_row”。这是我的代码......

$('.table_row').hover( function() {
    event.preventDefault();
    $(this).toggleClass('highlighted');
});

由于某种原因它不起作用,没有任何反应。该行不会响应任何事件。这是我用来创建表元素的代码,这是在上面的代码之前......

$('tbody').prepend(
    '<tr class="table_row"><td>' + results + '</td></tr>'
});

3 个答案:

答案 0 :(得分:4)

尝试使用:

$('tbody').on('mouseenter mouseleave', '.table_row', function() {
    $(this).toggleClass('highlighted');
});

这使用.on()为所有现有和未来.table_row元素设置事件处理程序。 .hover()mouseentermouseleave个事件绑定了处理程序,因此这与.hover()的工作方式相同。

您还可以考虑使用CSS :hover伪类。但是,如果您需要重用.highlighted类,这可能不是您要查找的内容。这是一个例子:

tbody > tr.table_row{ /* regular styles */}
tbody > tr.table_row:hover{
    // the current styles you have in .highlighted
}

答案 1 :(得分:3)

尝试使用事件委派,用于动态创建的元素。您的悬停事件仅绑定到该时间点存在的元素,因为您在运行时附加它们,您需要再次为新添加的行绑定事件或使用eventdelegation让您的容器将事件委托给动态行可用时。

$('yourtableselector').on('mouseenter mouseleave', '.table_row',  function() {
    $(this).toggleClass('highlighted');
});

<强> event-delegation

hovermouseenter/mouseleave

组合的虚拟事件

<强> Demo

答案 2 :(得分:3)

在悬停事件中使用CSS代替JavaScript进行简单的样式更改。

#my_table > tbody > tr:hover {
    background: yellow;
}

但是如果你确实使用了JavaScript,我建议创建元素,并直接绑定到它。

由于悬停事件在鼠标移动时频繁发生,我想让处理程序尽可能靠近元素。

$('<tr class="table_row"><td>' + results + '</td></tr>')
    .hover( function() {
        event.preventDefault();
        $(this).toggleClass('highlighted');
    })
    .appendTo("tbody");