JavaScript 事件委托没有实际事件?
希望我的标题不会太混乱。如果有更好的方法来解决我的问题,请告诉我。
我有 jQuery 函数,将背景颜色应用于表格中的奇数行,并在悬停时将颜色更改为红色。但是,如果我动态编辑表格,我的 jQuery 将不再工作。
我读了很多关于 JS 事件委托的内容,但找不到任何有关如何在没有实际事件的情况下使其工作的信息...
$(document).ready(function(){
//add background-color to all odd rows
//very important!!!
$("#tab3 tbody tr:odd").css("background-color", "#DCF1FD");
//change color on hover
//less important!!!
$("#tab3 tbody tr").hover(
function () {
$(this).css("color", "red");
},
function () {
$(this).css("color", "#000");
}
);
});
有没有办法在我编辑表格后使其工作。
编辑:
这必须在 IE8 上运行
Hope my title is not too confusing. Please let me know if there is a better way to title my problem.
I have jQuery function applying background-color to the odd rows in a table and on hover change the color to red. But if I edit the table dynamically my jQuery does not work any more.
I read a lot about JS event delegation and could not find any information about how to make this work without having actual event...
$(document).ready(function(){
//add background-color to all odd rows
//very important!!!
$("#tab3 tbody tr:odd").css("background-color", "#DCF1FD");
//change color on hover
//less important!!!
$("#tab3 tbody tr").hover(
function () {
$(this).css("color", "red");
},
function () {
$(this).css("color", "#000");
}
);
});
Is there a way to make it work after I edit the table.
EDIT:
This must work on IE8
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
即使您动态更新表行,在表上使用 jQuery
delegate
也能正常工作,因为事件附加到表而不是表的每一行。如果您要动态更新整个表格,则使用此
您可以使用简单的 css 设置奇数行的背景颜色
use jQuery
delegate
on the table that will work even if you update the table rows dynamically because the event is attached to table and not each rows of it.If you are updating the whole table dynamically then use this
You can set the background color of odd row with simple css
...或者您可以只使用 CSS 定义偶数行、奇数行和悬停状态的背景。请参阅此问题的第一个答案。
(编辑:固定链接,它指向错误的SO线程)。
... Or you could just use CSS to define the backgrounds for even rows, odd rows and the hover state. Se the first answer to this question.
(EDIT: fixed link, it was pointing the wrong SO thread).