如何将文档和类用作jQuery .hover()的选择器



,我需要使用"文档"作为事件的选择器的动态添加内容。

$(document).hover(function(){
  //Do something
}

现在我想知道我是否也可以将类用作选择器?
我尝试了:

$(document).hover('.liDoc', function(){
    $(this).children('.delDoc').css('color', 'red'); console.log($(this).children('.delDoc'))
}, function() {
    // on mouseout, reset the background colour
    $(this).children('.delDoc').css('color', '');
});

这个不起作用!似乎整个文档都是目标。
使用.on()时,我可以这样做...但是.on('hover')被弃用了吗?!

您需要委派mouseenter/mouseleave事件并按类型事件进行过滤,例如:

$(document).on('mouseenter mouseleave', '.liDoc', function(e) {
  $(this).children('.delDoc').css('color', e.type === "mouseenter" ? 'red' : '');
});

,但是您最好切换一类:

$(document).on('mouseenter mouseleave', '.liDoc', function(e) {
  $(this).children('.delDoc').toggleClass('colored');
});

与CSS:

.delDoc.colored {
  color: red;
}

或仅使用CSS,如果您的用例很简单,就像您发布的用例一样:

.liDoc:hover > .delDoc {
  color: red;
}

请尝试以下代码

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("p").hover(function(){
        $(this).css("background-color", "yellow");
        }, function(){
        $(this).css("background-color", "pink");
    });
});
</script>
</head>
<body>
<p>Hover the mouse pointer over this paragraph.</p>
</body>
</html>

您可以将类名称直接用作选择器。

当然,您需要首先导入jQuery库才能工作。

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min"></script>

如果您已经下载了jQuery库(推荐),则" SRC"值应导致文件。如果没有,您可以用上面的URL直接引用它。

现在,您的jQuery代码

<script>
    $(document).ready(function(){
        $(".liDoc").hover(function(){
            //mouse is in.. Do something
            $(this).children(".delDoc").css("background","red");
        }, function(){
            //mouse is out.. Do something
            $(this).children(".delDoc").css("background","transparent");
        });
    });
</script>

最新更新