javascript - 悬停时 undefined variable

标签 javascript jquery html css hover

我有两个列表,当我在一个列表中将鼠标悬停在 Tom 上时,我希望关于他的描述变为红色,因此我添加了一个悬停类,如下所示。 我遇到的问题是我无法删除悬停状态,因为当我离开悬停状态时我变得不确定。我已经评论了到目前为止我尝试过的几件事。 当我离开悬停时,有没有办法知道 id 的值或删除页面上任何名为 hover 的类?

    <ul id="one-list">
        <li id="u11">Tom</li>
        <li id="u22">Jerry</li>
    </ul>

    <ul id="another-list">
        <li id="a11">Tom is 22 years old</li>
        <li id="a22">Jerry is 18 years old</li>
    </ul>

    $("#one-list li").hover(

    function () {
        var id = jQuery(this).attr('id') || '';
        id = id.replace(/u/, '');
        $('#another-list #a' + id ).addClass("hover");
    }, function () {
        //$('body').removeClass("hover");
        //$('#another-list #a' + id ).removeClass("hover");
    }
    );

    .hover {
        color:red;
    }

最佳答案

您收到该错误是因为 id 仅在第一个函数中定义。您需要在第二个函数中再次获取 id,例如:

$("#one-list li").hover(
    function () {
        var id = jQuery(this).attr('id') || '';
        id = id.replace(/u/, '');
        $('#another-list #a' + id ).addClass("hover");
    }, function () {
        var id = jQuery(this).attr('id') || '';
        id = id.replace(/u/, '');
        $('#another-list #a' + id ).removeClass("hover");
    }
);

或者更简单

$("#one-list li").hover(
    function () {
        var id = this.id.replace('u', '');
        $('#another-list #a' + id ).addClass("hover");
    }, function () {
        var id = this.id.replace('u', '');
        $('#another-list #a' + id ).removeClass("hover");
    }
);

或者更好:

 $("#one-list li").hover(
    function () {
        var id = this.id.replace('u', '');
        $('#another-list #a' + id ).toggleClass("hover");
    }
 );

关于javascript - 悬停时 undefined variable ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20693248/

相关文章:

javascript - 是否可以在 d3js 准备就绪时触发事件?

javascript - 循环中的变量

javascript - 如何在 html 页面加载结束时执行任何特定操作或事件

javascript - 在 Zingchart 中定义 'step' 属性会导致图形不可用

javascript - JavaScript 如何处理模数?

javascript - 如何使子应用程序可以访问 session 变量

JavaScript 语法结构

javascript - 根据复选框选择显示/隐藏选项卡

javascript - get如何获取动态生成的值

javascript - 如何使用以下代码停止 "fixed"元素?