简体   繁体   中英

jquery - on hover li width id - show the matching id div

<ul class="level0">
<li class="level1" id="cat2441"></li>
<li class="level1" id="cat2450"></li>
<li class="level1" id="cat2455"></li>
</ul>

<div class="alles-zwei" id="new-cat2441"></div>
<div class="alles-zwei" id="new-cat2450"></div>
<div class="alles-zwei" id="new-cat2455"></div>

Hallo, on hover the li(id) element I would like to show the matching div(id) – and hover an another li (wrong id) or leaving the ul I would like to hide the div

my approach was

jQuery('.alles li').mouseover(function() {
    var cat = '"#new-' + this.id + '"';
    jQuery(cat).fadeIn();
});

You were using the wrong selectors. Also '"#new-' + this.id + '"' this syntax is wrong. There is no need to add those double quotes inside the string.

 jQuery('.level0 li').hover(function() { var cat = '#new-' + this.id; jQuery(cat).show(); }, function() { var cat = '#new-' + this.id; jQuery(cat).hide(); }); 
 .alles-zwei { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script> <ul class="level0"> <li class="level1" id="cat2441">cat2441</li> <li class="level1" id="cat2450">cat2450</li> <li class="level1" id="cat2455">cat2455</li> </ul> <div class="alles-zwei" id="new-cat2441">cat2441</div> <div class="alles-zwei" id="new-cat2450">cat2450</div> <div class="alles-zwei" id="new-cat2455">cat2455</div> 

You could do this without having to rely on the id of the element just use the class of the two elements. When you select the class it gets returned as an array so you can match the level1 class array with the alles-zwei class array. It will also simplify your HTML code.

$('.level1').hover(function(){
    // Gets the index of the current li emement.
    var indx = $(this).index(); 

    // Gets the div element based on the hovered li and hides its siblings.
    $('.alles-zwei').eq(indx).show().siblings('div').hide();
});

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