我还在学习,我有个小问题。
我有三个链接,我想知道我给点击哪个链接。这就是我的链接:
<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 有人能解释我错过了什么吗?非常感谢!!
:)
发布于 2016-07-01 00:07:57
看到我的评论靠近每一行
/* 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发布于 2016-06-30 23:55:36
我希望这能帮到你。
// 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很久之后)。
https://stackoverflow.com/questions/38135001
复制相似问题