gpt4 book ai didi

javascript - 在方法 JQuery 之外使用我的变量

转载 作者:行者123 更新时间:2023-12-03 06:37:19 24 4
gpt4 key购买 nike

我还在学习,我有一个小问题。

我有三个链接,我想知道我点击了哪个链接。所以,这是我的链接:

<ul id="links">
<li><a id="map-1" href="#">Mapa 1</a></li>
<li><a id="map-2" href="#">Mapa 2</a></li>
<li><a id="map-3" href="#">Mapa 3</a></li>
</ul>

这是我的 JS

var currentLink;

$(document).ready(function(){
$("#links a").each(function(){
$(this).on("click", function(e){
return currentLink= $(this).attr("id");
console.log(currentLink); //This works 'cause I know the ID of my current link
});
});
});
console.log(currentLink); //I lost the value of my link

有人可以解释一下我错过了什么吗?非常感谢!!

:)

最佳答案

  • Your question is not clear but here is what is happening
  • You need to tell us what exactly you are looking for

See my comments near each line

/* Variable is defined here*/
var currentLink;

/*document ready, means this executes after your page is loaded and dom is ready*/
$(document).ready(function(){
$("#links a").each(function(){
$(this).on("click", function(e){
return currentLink= $(this).attr("id");
console.log(currentLink); /***This is wrong, not sure how it works, after you return something this line is not supposed to be executed.***/
});
});
});

//This gets executed immediately before document ready is ran, probably first
console.log(currentLink); //YOUR VALUE IS NEVER assigned here while it is executing

关于javascript - 在方法 JQuery 之外使用我的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38135001/

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