hQuery在悬停时显示/隐藏特定<li> </li>中的div

时间:2013-06-19 03:59:04

标签: javascript jquery html

我有一个显示列表的页面,用户可以添加和删除项目。

在每个<li></li>上,有一个与项目匹配的小删除按钮。

现在,删除按钮仅在用户悬停列表时显示。 我试图做的只是在用户将鼠标悬停在特定项目上时显示一个删除按钮。

这是我到目前为止所拥有的:

$(document).ready(function() {
    $(".delete_update").hide(); 
    $('.cell').hover(function(){
        $(".delete_update").show();

        $('.cell').mouseout(function(){
            $(".delete_update").hide();
        });
    });
});


<li class="cell" id="post<?php echo $postid ?>">
    <div id="update<?php echo $postid ?>">
        <?php echo $post ?>
    </div>
    <div id="eraser<?php echo $postid ?>">
        <a href="#" id="<?php echo $postid ?>" class="delete_update">Delete !</a>
    </div>
</li>

我尝试在jQuery中添加一个变量来包含&#34; id&#34;每个细胞,似乎:

var element = $(this);
var I = element.attr("id");
$('.cell' + I).hover(function() {
    $(".delete_update").show();
});

但这不会起作用。

有什么想法吗?

4 个答案:

答案 0 :(得分:3)

试试这个:

$(function(){
    $('.cell').hover(function(){ //Hover takes 2 callbacks one for mouseenter and one for mouseleave
          $(this).find('.delete_update').show(); //show the button which is inside the current li hovered
    },
     function(){
         $(this).find('.delete_update').hide(); //hide the button which is inside the current li hovered

     });
});

或者只是使用切换

 $(function(){
        $('.cell').hover(function(){ // Same callback will be executed if only one is mentioned,  on mouseeneter and mouse leave
              $(this).find('.delete_update').toggle(); //toggle the button visibility which is inside the current li hovered
        }
    });

答案 1 :(得分:3)

Pehaps使用CSS!

.delete_update
{
    display:none;
}

.cell:hover .delete_update
{
    display:block;
}

看到这个小提琴:http://jsfiddle.net/htqkt/1/

当然你没有得到jquery的花哨传递,但是你可以使用CSS过渡在现代浏览器中实现同样的东西

答案 2 :(得分:2)

使用上下文选择器

$(document).ready(function(){
    $(".delete_update").hide(); 
    $('.cell').hover(function(){
        $(".delete_update", this).show();
    }, function(){
        $(".delete_update", this).hide();
    });
});

$(document).ready(function(){
    $(".delete_update").hide(); 
    $('.cell').hover(function(){
        $(".delete_update", this).toggle();
    });
});

答案 3 :(得分:1)

变化:

$(".delete_update").show();

$(this).find(".delete_update").show();

$(".delete_update",this).show();