jQuery选择器父母和孩子?

时间:2009-09-01 12:16:57

标签: jquery

我想要一些类似于Wordpress对帖子做的事情 - 行动。

我的HTML

<div class="onhover">
  <p class="">This is a paragraph. My background will be yellow when you hover over me — even if you're using Internet Explorer.</p>
  <div class="actions"><a href="#">Add</a> | <a href="#">Edit</a> | <a href="#">Modify</a> | <a href="#">Delete</a></div>  
</div>
<div class="onhover">  
  <p class="">Move your mouse over me! Move your mouse over me! I'll turn yellow, too! Internet Explorer users welcome!</p>
  <div class="actions"><a href="#">Add</a> | <a href="#">Edit</a> | <a href="#">Modify</a> | <a href="#">Delete</a></div>
</div>

CSS

* { margin:0; padding:0; font-family:Verdana, Arial, Helvetica, sans-serif; }
    div.actions { padding:5px; font-size:11px; visibility: hidden; }
    #hover-demo1 p:hover {
        background: #ff0;
    }
    .pretty-hover {
        background: #fee;
        cursor: pointer;
    }

Jquery的

$(document).ready(function() {
      $('.onhover p').hover(function() {
        $(this).addClass('pretty-hover');
        $('div.actions').css('visibility','visible');
      }, function() {
        $(this).removeClass('pretty-hover');
        $('div.actions').css('visibility','hidden');
      });
    });

我想要的是,在悬停特定P元素时,相应的操作应该是可见的,当前在悬停p元素时,所有其他操作都是可见的。我如何限制特定的人?

2 个答案:

答案 0 :(得分:2)

无需设置CSS可见性属性。有jQuery方法可以隐藏和显示事物。只需使用next()遍历方法。

$(document).ready(function() {
  $('.onhover p').hover(function() {
    $(this).addClass('pretty-hover');
    $(this).next().show();
  }, function() {
    $(this).removeClass('pretty-hover');
    $(this).next().hide();
  });
});

答案 1 :(得分:0)

可能首先隐藏所有div.actions,并仅在父母被悬停时显示:

$(document).ready(function() {
  $('div.actions').hide();
  $('.onhover p').hover(function() {
    $(this).addClass('pretty-hover');
    $(this).children('div.actions:first').show();
  }, function() {
    $(this).removeClass('pretty-hover');
    $(this).children('div.actions:first').hide();
  });
});