gpt4 book ai didi

javascript - 在(文档)内设置变量。准备好使用所有功能了吗?

转载 作者:行者123 更新时间:2023-11-28 15:43:46 25 4
gpt4 key购买 nike

对 jQuery 来说真的很陌生,这让我困惑了一段时间。

我将以此为例:

$(document).ready(function(){

$("#link1 a").hover(function(){
var $this = $(this);
$this.css("color", "#fff");
});
});

显然,这会将鼠标悬停时 #link1 内的 a 颜色更改为白色。

这就是我想要做的:

    $(document).ready(function(){

var $this = $(this);

$("#link1 a").hover(function(){
$this.css("color", "#fff");
});

$("#link2 a").hover(function(){
$this.css("color", "#f00");
});
});

这不起作用。

我可以设置 var $this = $(this);在(文档)内。准备好了吗?它可以与其中的所有功能一起使用吗?

抱歉,如果这是一个愚蠢的问题,在其他地方找不到答案。老实说,我并不是 100% 确定要搜索!

最佳答案

您的声明 var $this = $(this); 虽然有效,但未达到您的需求。如果您考虑一下...这是指 $(document)

所以,如果您将代码更改为:

$(document).ready(function(){

$("#link1 a").hover(function(){
var $this = $(this);
$this.css("color", "#fff");
}); //In this case $this refers to $("#link1 a")

$("#link2 a").hover(function(){
var $this = $(this);
$this.css("color", "#f00");
}); //In this case $this refers to $("#link2 a")
});

但是,这并不是真正必要的,因为您可以这样做:

$(document).ready(function(){

$("#link1 a").hover(function(){
$(this).css("color", "#fff");
});

$("#link2 a").hover(function(){
$(this).css("color", "#f00");
});
});

现在,如果您想增加 $this 的范围,您可以这样做:

$(a).hover(function() {
var $this = $(this);

//now if you wanted to check for which link is currently hovered you can say this :
var link = $this.attr("id");
//this will set link equal to the current id

//NOW you can have if statements checking which link it is...
if(link == "link1") { ... do stuff }
if(link == "link2") { ... do other stuff }
}

另外,如果您使用的是 JQuery 版本 POST 1.7,您应该像这样调用事件:

$(a).on("hover", function () {
...some function
});

最后,不要害怕查看 JQuery API 来获取一些帮助......它写得很好并提供了示例

https://api.jquery.com/

关于javascript - 在(文档)内设置变量。准备好使用所有功能了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23021527/

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