Use jquery to bind an instance of hover event to a new th

  • 2021-07-18 06:45:17
  • OfStack

This is a small problem encountered when doing a dynamic table yesterday. th of table needs to show color changes when the mouse moves in and out. th was written dead before, which can be directly realized by hover () method of jquery. Now th needs js/ajax to dynamically generate and load to the page, and hover () has no effect (because mouseover and mouseout events have to be re-bound to th, and considering that th may be loaded many times, bind has to be bound many times, which is troublesome). Here I use live to solve the problem of binding hover events to new th:

The code is as follows:


$(function(){
 //....
 $("th").live("mouseover",function(){
    $(this).attr("style","color:#EE7600;font-weight:bold");
  }).live("mouseout",function(){
    $(this).removeAttr("style");
  });
 //....
});

Very simple 1 piece of code, use live () twice to bind mouseover and mouseout events to th, because. live () method is using event delegate, can be added to an DOM element is effective, so as long as live is used once in jq, it will have an effect on the elements loaded later.


Related articles: