简体   繁体   中英

Jquery each show its div

Trying to add some hover functionality to a div and I seem to be missing something. When hovering over a div element show it's nearest div with a class of .stat. I can get the hover state to work on each div but I can't get the nearest div to hover, or any div.

Thanks

Code is:

    $(".stat-button").each(function(i){
$(this).mouseover(function () {
        console.log('hover');
      $(".stat").find(i).show();
}).mouseout(function () {
        $(".stat").find(i).hide();
});
 });

Link to jsfiddle: https://jsfiddle.net/qo1x03q5/

Use the jQuery siblings() method to select the .stat that is a sibling of the .stat-button that is being hovered over:

$(".stat-button").mouseover(function () {
    console.log('hover');
    $(this).siblings(".stat").show();
}).mouseout(function () {
    $(this).siblings(".stat").hide();
});

JSFiddle Demo

Use Jquery $.siblings to get the sibling elements.

You can also use $.hover instead of $.mouseover and $.mouseout .

$(".stat-button").hover(function(){
  console.log('hover');
  $(this).siblings(".stat").show();
},
function(){
  $(this).siblings(".stat").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