gpt4 book ai didi

javascript - 悬停时 undefined variable

转载 作者:太空宇宙 更新时间:2023-11-03 23:49:11 25 4
gpt4 key购买 nike

我有两个列表,当我在一个列表中将鼠标悬停在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com