[英]no triggering on click event
This is a simple but intersting issue. 这是一个简单但有趣的问题。 Suppose I have two sections of respective class
.toggle0
and .toggle1
, suppose I want to display .toggle0
and hide .toggle1
when clicking on some tag .footer0
, and vice-versa : I want to display .toggle1
and hide .toggle0
when clicking on some tag .footer1
. 假设我有各自的类两个部分
.toggle0
和.toggle1
,假设我想显示.toggle0
和隐藏.toggle1
一些标签,当点击.footer0
,反之亦然:我想显示.toggle1
和隐藏.toggle0
当点击在一些标签.footer1
。 Now this code works correctly 现在此代码可以正常工作
$('.toggle1').hide();
var i=0;
$(".footer"+i+"").click(function(){
$(".toggle"+(i+1) %2+"").hide();
$(".toggle"+i+"").show();
});
var j=1;
$(".footer"+j+"").click(function(){
$(".toggle"+(j+1) %2+"").hide();
$(".toggle"+j+"").show();
});
but this doesn't work in the sense that nothing happens on click event 但这在点击事件无反应的意义上不起作用
for(var i=0;i<2;i++){
$(".footer"+i+"").click(function(){
$(".toggle"+(i+1) %2+"").hide();
$(".toggle"+i+"").show();
});
}
if I put this 如果我把这个
$('.toggle1').hide();
var i=0;
$(".footer"+i+"").click(function(){
$(".toggle"+(i+1) %2+"").hide();
$(".toggle"+i+"").show();
});
i =1;
$(".footer"+i+"").click(function(){
$(".toggle"+(i+1) %2+"").hide();
$(".toggle"+i+"").show();
});
.toggle1
displays and .toggle0
hides when clicking on some tag .footer1
but .toggle0
does not display and .toggle1
does not hide when clicking on some tag .footer0
. .toggle1
显示器和.toggle0
一些标签,当点击隐藏.footer1
但.toggle0
不显示和.toggle1
一些标签点击时不会隐藏.footer0
。 It seems that the second click event takes precedence upon the first 似乎第二个点击事件优先于第一个点击事件
The i
within the the click handler isn't evaluated until a click, at which point the value has changed from when the handler was bound. 单击处理程序中的
i
直到单击后才进行评估,此时该值从绑定处理程序时开始更改。 If you want to go this route, you need to create a closure. 如果要走这条路线,则需要创建一个闭合。 Here's one method to do so:
这是这样做的一种方法:
for (var i = 0; i < 2; i++) {
$(".footer" + i + "").click(function () {
var idx = i;
return function () {
$(".toggle"+(idx+1) %2+"").hide();
$(".toggle"+idx+"").show();
console.log(idx);
}
}());
}
$('.footer0').click(function(){
$('.toggle0 .toggle1').hide();
$('.toggle0').show();
});
$('.footer1').click(function(){
$('.toggle0 .toggle1').hide();
$('.toggle1').show();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.