开发者

How to call mouse over function on dyanamic divs

I have dynamic divs as rows:

<table border=1&g开发者_StackOverflowt;<tr><td>
<div id='div1'>fgg</div>
<div id='div2'>dfgdfg</div>
<div id='div3'>vcbcvb</div>
<div id='div4'>sdfsdf</div>
</td></tr></table>

How can I call jQuery function on mouseover of each div? These divs are dynamic, can vary the number.


$("td div").live("mouseover", function() {
 //mouseover code here
});

I suggest using a class for your divs, and using a selector: $(".rows") or similar. However, the above will work for the markup you've given.

If you must use id, this will allow you to add it by id. Keep in mind that as you add new items, you will have to run this code for the id (defeating the dynamic part of your original question).

$("#mydivid").mouseover(function() {
  //mouseover code here
});

which you could utilize in a list like so:

var divs = ["mydiv1", "mydiv2", "mydiv3"];
$(divs).each(function() {
  $("#" + this).mouseover(function() {
    //mouseover code here
  });
});

This is really a bad approach, I strongly suggest using a class instead.


Use event delegation, either .live() or .delegate() to bind events to elements that are created dynamically.


one another easy way is to give the same class name to all the divs. you can hook the click event by class name instead of id.In the code you can also refer the current div block by using "this" keyword


Unless there is some reason you specifically cannot use a repeating class name for each div, the live() method is the way to go. Using a class would be much more efficient, however.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜