tags:

views:

120

answers:

3

Hi all,

I am learning JQuery.

<Div ID="top">
<DIV ID="testing1">
<DIV ID="testing2"><DIV ID="testing3">...<DIV ID="testing100"></Div>

Since there are tens of DIV tags with different ID generated by a PHP file And I am trying to pass a dynamic ID of a DIV tag to a JQuery self-defined function:

<script>$(function() {
 $("div").mouseover(function() {
      var ID = $(this).children().attr('id');
      alert(ID);     });}); </script>

But it wont work.

+1  A: 

If you want the ID of the DIV that triggered the event, you can just use $(this).id() instead of the $(this).children().attr("id").

children() would give you an array of all elements that are inside your DIV. But getting one ID from a list of multiple elements will be kind of problematic ;)

if you want the ID of the first element inside your DIV, try $(this).children().first().id().

Techpriester
You can use `this.id` inside the event handler. No need to wrap in jquery, since jquery takes care of it being in context.
nikc
@nikc: Right. That'd work, too.
Techpriester
+1  A: 

Remove the .children() - you want the id attribute of the div, so you don't need to go to its children for that.

Also, you can use .id() instead of .attr('id').

Thus, it becomes simply $(this).id() to get the id of the element on which the function was invoked.

Amber
A: 

The following example works, and event bubbling results in three calls, each in turn giving an id of "testing2", "testing1" and then "top" in that order.

<div id="top">
    <div id="testing1">
        <div id="testing2">x</div>
    </div>
</div>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript">
$(function () {
    $("div").mouseover(function () {
        var ID = this.id;
        alert(ID);     
    });
});
</script>
Sohnee