我还在学习,我有一个小问题。
我有三个链接,我想知道我点击了哪个链接。所以,这是我的链接:
<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
有人可以解释我错过了什么吗? 非常感谢!!
:)
答案 0 :(得分:2)
- 你的问题不明确,但现在正在发生的事情
- 你需要告诉我们你究竟在寻找什么
查看我在每行附近的评论
/* 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
答案 1 :(得分:-1)
我希望这会有所帮助。
// 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
之后很久)。