Javascript 替代支持 eventData 的 jQuery .toggle() 方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2459153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Alternative to jQuery's .toggle() method that supports eventData?
提问by Bungle
The jQuery documentationfor the .toggle()method states:
在jQuery文档的.toggle()方法规定:
The .toggle() method is provided for convenience. It is relatively straightforward to implement the same behavior by hand, and this can be necessary if the assumptions built into .toggle() prove limiting.
提供 .toggle() 方法是为了方便。手动实现相同的行为相对简单,如果 .toggle() 中内置的假设证明是有限的,那么这可能是必要的。
The assumptions built into .togglehave proven limiting for my current task, but the documentation doesn't elaborate on how to implement the same behavior. I need to pass eventData to the handler functions provided to toggle(), but it appears that only .bind()will support this, not .toggle().
内置的假设.toggle已经证明对我当前的任务有限制,但文档没有详细说明如何实现相同的行为。我需要将 eventData 传递给提供给 的处理函数toggle(),但似乎只.bind()支持这个,而不支持.toggle().
My first inclination is to use a flag that's global to a single handler function to store the click state. In other words, rather than:
我的第一个倾向是使用一个对单个处理程序函数全局的标志来存储单击状态。换句话说,而不是:
$('a').toggle(function() {
alert('odd number of clicks');
}, function() {
alert('even number of clicks');
});
do this:
做这个:
var clicks = true;
$('a').click(function() {
if (clicks) {
alert('odd number of clicks');
clicks = false;
} else {
alert('even number of clicks');
clicks = true;
}
});
I haven't tested the latter, but I suspect it would work. Is this the best way to do something like this, or is there a better way that I'm missing?
我没有测试后者,但我怀疑它会起作用。这是做这样的事情的最佳方式,还是我缺少的更好的方式?
Thanks!
谢谢!
回答by Alconja
Seems like a reasonable way to do it... I'd just suggest that you make use of jQuery's data storageutilities rather than introducing an extra variable (which could become a headache if you wanted to keep track of a whole bunch of links). So based of your example:
似乎是一种合理的方法……我只是建议您使用 jQuery 的数据存储实用程序,而不是引入额外的变量(如果您想跟踪一大堆链接,这可能会让人头疼) . 所以基于你的例子:
$('a').click(function() {
var clicks = $(this).data('clicks');
if (clicks) {
alert('odd number of clicks');
} else {
alert('even number of clicks');
}
$(this).data("clicks", !clicks);
});
回答by Asad Saeeduddin
Here is a plugin that implements an alternative to .toggle(), especially since it has been removed in jQuery 1.9+.
这是一个实现替代 的插件.toggle(),特别是因为它已在 jQuery 1.9+ 中删除。
How to use:
如何使用:
The signature for this method is:
此方法的签名是:
.cycle( functions [, callback] [, eventType])
functions[Array]: An array of functions to cycle betweencallback[Function]: A function that will be executed on completion of each iteration. It will be passed the current iteration and the output of the current function. Can be used to do something with the return value of each function in thefunctionsarray.eventType[String]: A string specifying the event types to cycle on, eg."click mouseover"
functions[Array]:要循环的函数数组callback[Function]:每次迭代完成时将执行的函数。它将传递当前迭代和当前函数的输出。可用于处理functions数组中每个函数的返回值。eventType[String]:指定要循环的事件类型的字符串,例如。"click mouseover"
An example of usage is:
一个使用示例是:
$('a').cycle([
function() {
alert('odd number of clicks');
}, function() {
alert('even number of clicks');
}
]);
I've included a demonstration here.
我在这里包含了一个演示。
Plugin code:
插件代码:
(function ($) {
if (!Array.prototype.reduce) {
Array.prototype.reduce = function reduce(accumulator) {
if (this === null || this === undefined) throw new TypeError("Object is null or undefined");
var i = 0,
l = this.length >> 0,
curr;
if (typeof accumulator !== "function") // ES5 : "If IsCallable(callbackfn) is false, throw a TypeError exception."
throw new TypeError("First argument is not callable");
if (arguments.length < 2) {
if (l === 0) throw new TypeError("Array length is 0 and no second argument");
curr = this[0];
i = 1; // start accumulating at the second element
} else curr = arguments[1];
while (i < l) {
if (i in this) curr = accumulator.call(undefined, curr, this[i], i, this);
++i;
}
return curr;
};
}
$.fn.cycle = function () {
var args = Array.prototype.slice.call(arguments).reduce(function (p, c, i, a) {
if (i == 0) {
p.functions = c;
} else if (typeof c == "function") {
p.callback = c;
} else if (typeof c == "string") {
p.events = c;
}
return p;
}, {});
args.events = args.events || "click";
console.log(args);
if (args.functions) {
var currIndex = 0;
function toggler(e) {
e.preventDefault();
var evaluation = args.functions[(currIndex++) % args.functions.length].apply(this);
if (args.callback) {
callback(currIndex, evaluation);
}
return evaluation;
}
return this.on(args.events, toggler);
} else {
//throw "Improper arguments to method \"alternate\"; no array provided";
}
};
})(jQuery);

