In jQuery how to specify mouseover event priority for a child

My question is: how do I prioritize the detection of a "mouseover" event for a child and not its parent?

this is jquery code:

<script>
$(function() {
    $("li").mouseover(function(event){
        $('#log').html($(this).text());
    });
}); 
</script>   

and this is the html code

  <ul>
     <li>item 1</li>
     <li>item 2</li>
     <li>item 3
        <ul>
           <li>item 3.1</li>
           <li>item 3.2</li>
           <li>item 3.3</li>
        </ul>
     </li>
     <li>item 4</li>
  </ul>

  <div id="log">log</div>

How to display the current item when the mouse is executed?

the problem is that you hover over “item 3.1”, jquery won't detect “element 3.1” and instead jquery supposes you hover over “item 3”?

thank

+3
source share
4 answers

Do you want the purpose of the event :

$("li").mouseover(function(event) {
    $('#log').html($(event.target).text());
});

From quirksmode (linked above):

Even if the event is captured or bubbles up, the target / srcElement always remains the event element held.

Demo is here.

+6

span li ,

<script>
$(function() {
    $("li span").mouseover(function(event){
        $('#log').html($(this).text());
    });
}); 
</script>   

<ul>
    <li><span>item 1</span></li>
    <li><span>item 2</span></li>
    <li><span>item 3</span>
        <ul>
           <li><span>item 3.1</span></li>
           <li><span>item 3.2</span></li>
           <li><span>item 3.3</span></li>
        </ul>
    </li>
    <li><span>item 4</span></li>
</ul>

<div id="log">log</div>
+1

"li" "li".

For example, you can add class='innerItem"to inner 'li', for example:

<li class='innerItem'>item 3.1</li>

Then your jQuery should look like this:

<script>
    $(function() {
        $("li.innerItem").mouseover(function(event){
        $('#log').html($(this).text());
    });
}); 
</script>
0
source

Here is an alternative to Karim79.

$("li").mouseover(function(event){
    $('#log').html($(this).text());
    event.stopPropagation();
});

Be sure to actually read stopPropagation () .

http://jsbin.com/afunu3

0
source

All Articles