首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在方法JQuery之外使用我的变量

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

Stack Overflow用户
提问于 2016-06-30 23:52:24
回答 2查看 56关注 0票数 0

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

我有三个链接,我想知道我给点击哪个链接。这就是我的链接:

代码语言:javascript
复制
<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

代码语言:javascript
复制
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 

有人能解释我错过了什么吗?非常感谢!!

:)

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-07-01 00:07:57

  • 你的问题还不清楚,但这里是发生了什么
  • 你得告诉我们你到底在找什么

看到我的评论靠近每一行

代码语言:javascript
复制
/* 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
票数 2
EN

Stack Overflow用户

发布于 2016-06-30 23:55:36

我希望这能帮到你。

代码语言:javascript
复制
// This line runs first.
var currentLink;

$(document).ready(function () {
   $("#links a").each(function () {
       $(this).on("click", function (e) {
          // This line runs third.
          return currentLink = $(this).attr("id");
          console.log(currentLink); // This never runs, since there's a "return" above it.
       });
   });
}); 

// This line runs second.
console.log(currentLink);

编辑

详细说明:首先创建变量。然后设置一个单击处理程序。然后记录变量的值。然后在将来的某个时候,当有人单击某个链接时,您的单击处理程序将实际运行,您将为该变量指定一个值(在执行console.log很久之后)。

票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/38135001

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档