jQuery单击/切换两个函数 [英] jQuery click / toggle between two functions
问题描述
我正在寻找一种方法,在点击某些内容时运行两个单独的操作/函数/代码块,然后在再次单击相同的内容时运行完全不同的块。我把它放在一起。我想知道是否有更有效/更优雅的方式。我知道jQuery .toggle()但它很糟糕。
I am looking for a way to have two separate operations / functions / "blocks of code" run when something is clicked and then a totally different block when the same thing is clicked again. I put this together. I was wondering if there was a more efficient / elegant way. I know about jQuery .toggle() but it kind of sucks.
在此工作:
http://jsfiddle.net/reggi/FcvaD / 1 /
var count = 0;
$("#time").click(function() {
count++;
//even odd click detect
var isEven = function(someNumber) {
return (someNumber % 2 === 0) ? true : false;
};
// on odd clicks do this
if (isEven(count) === false) {
$(this).animate({
width: "260px"
}, 1500);
}
// on even clicks do this
else if (isEven(count) === true) {
$(this).animate({
width: "30px"
}, 1500);
}
});
推荐答案
jQuery有两种方法叫做 .toggle()
。 其他 [docs] 完全符合你想要的点击事件。
jQuery has two methods called .toggle()
. The other one [docs] does exactly what you want for click events.
注意:似乎至少从 jQuery 1.7 开始,这个 .toggle
的版本已弃用,可能正是出于这个原因,即存在两个版本。使用 .toggle
来更改元素的可见性只是一种更常见的用法。该方法在jQuery 1.9中被删除。
Note: It seems that at least since jQuery 1.7, this version of .toggle
is deprecated, probably for exactly that reason, namely that two versions exist. Using .toggle
to change the visibility of elements is just a more common usage. The method was removed in jQuery 1.9.
下面是一个如何实现与插件相同功能的示例(但可能会暴露与内置版本相同的问题(参见文档中的最后一段))。
Below is an example of how one could implement the same functionality as a plugin (but probably exposes the same problems as the built-in version (see the last paragraph in the documentation)).
(function($) {
$.fn.clickToggle = function(func1, func2) {
var funcs = [func1, func2];
this.data('toggleclicked', 0);
this.click(function() {
var data = $(this).data();
var tc = data.toggleclicked;
$.proxy(funcs[tc], this)();
data.toggleclicked = (tc + 1) % 2;
});
return this;
};
}(jQuery));
(免责声明:我不是说这是最好的实施!我打赌它可以在性能方面得到改善)
然后用以下方式调用:
$('#test').clickToggle(function() {
$(this).animate({
width: "260px"
}, 1500);
},
function() {
$(this).animate({
width: "30px"
}, 1500);
});
更新2:
与此同时,我为此创建了一个合适的插件。它接受任意数量的函数,可用于任何事件。 它可以在GitHub上找到。
In the meantime, I created a proper plugin for this. It accepts an arbitrary number of functions and can be used for any event. It can be found on GitHub.
这篇关于jQuery单击/切换两个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!