简体   繁体   中英

How to call mouse over function on dyanamic divs

I have dynamic divs as rows:

<table border=1><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.

使用事件委托.live().delegate()将事件绑定到动态创建的元素。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM