我有一些奇怪的行为。我想在点击span
标签时触发事件,假设#span
id。当我在控制台中运行它时,要测试:
$('#span').toggle(function(){
console.log('hi');
},function(){
console.log('hey');
});
#span
显示设置为无。我试图找到一些可能干扰的代码,但我没有找到任何...
这个版本的切换在jQuery 1.9中删除了,所以如果你使用的是jQuery>= 1.9,它将切换显示状态
启用已删除功能的一种可能的解决方案是在jQuery之后添加迁移插件
另一个将是自己编写一个切换点击插件,就像这个答案中的下面一样
$.fn.toggleClick = function(){
var methods = arguments, // store the passed arguments for future reference
count = methods.length; // cache the number of methods
//use return this to maintain jQuery chainability
return this.each(function(i, item){
// for each element you bind to
var index = 0; // create a local counter for that element
$(item).click(function(){ // bind a click handler to that element
return methods[index++ % count].apply(this,arguments); // that when called will apply the 'index'th method to that element
// the index % count means that we constrain our iterator between 0 and (count-1)
});
});
};
然后
$('#span').toggleClick(function(){
console.log('hi');
},function(){
console.log('hey');
});
Jquery 不再支持toggle(func,func)
,toggle()
只是将元素切换visible
或invisible
。
http://api.jquery.com/category/deprecated/
.toggle() 方法签名在 jQuery 1.8 中被弃用,并在 j查询 1.9.jQuery还提供了一个名为.toggle()的动画方法。 这将切换元素的可见性。无论是动画还是 触发的事件方法取决于传递的参数集。
http://api.jquery.com/toggle-event/
你可以使用 .one()
演示
function handler1() {
console.log('hi');
$(this).one("click", handler2);
}
function handler2() {
console.log('hey');
$(this).one("click", handler1);
}
$("#span").one("click", handler1);
它已被弃用,然后在 jQuery 1.9
中删除。你可以在这里找到一些文档
jquery 1.9 中不再有切换(以这种方式)。
您可以做的是这样做并制作自己的类似切换的插件:
$.fn.toggleFn = function(){
var fns = arguments;
var fns_length = fns.length;
var idx = 0;
this.on('click', function(){
fns[idx % fns_length].apply(this, arguments);
idx++;
});
}
使用它:
$('#span').toggleFn(function(){
console.log('hi');
},function(){
console.log('hey');
});