【问题标题】:using jquery each to show/hide on hover使用 jquery each 在悬停时显示/隐藏
【发布时间】:2011-10-27 20:01:44
【问题描述】:

我与“myanchor”类有几个链接。 我想为每个链接显示一个 div(onmouseover)并隐藏(onmouseout):

“link1”显示“div1” “link2”显示“div2” . . .

我的代码不起作用:

$(document).ready(function () {
        var n = $(".myanchor").length;
        var arr = [];
        for (var i = 1; i <= n; i++) {
            arr[i] = i;
        };

        jQuery.each(arr, function () {
            $("#anchor" + this, "#div" + this).mouseover(function () {
                $("#div" + this).show();
            }).mouseout(function () {
                $("#div" + this).hide();
            });
        });
    });

谢谢。

【问题讨论】:

    标签: jquery each onmouseover


    【解决方案1】:

    这样的事情应该可以解决问题。我假设链接名称存储在链接的id 属性中:

    $(".myanchor").hover(function() {
        var id = $(this).attr("id");
        $("#div" + id.charAt(id.length - 1)).show();
    }, function() {
        var id = $(this).attr("id");
        $("#div" + id.charAt(id.length - 1)).hide();
    });
    

    这是working example。这消除了对each 循环的需要,因为jQuery 方法倾向于应用于匹配集中的所有元素(在这种情况下,这就是所有.myanchor 元素)。使用hover 只是比分别绑定mouseovermouseout 短一点,但最终结果是一样的。

    【讨论】:

    • 谢谢,这是一个干净的代码,但我也希望当我将鼠标悬停在 div 上时它保持可见,当我将鼠标悬停在 div 上时它被隐藏
    【解决方案2】:

    这应该有效:

    $(document).ready(function () {
                $(".myanchor").each(function(i){
                  $(this).mouseover(function () {
                        $("#div" + i).show();
                    }).mouseout(function () {
                        $("#div" + i).hide();
                    });
                });
            });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-07-21
      • 2010-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-06-12
      • 2012-06-22
      相关资源
      最近更新 更多