jQuery documentation对于 .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
中内置的假设已证明对我当前的任务有限制,但文档没有详细说明如何实现相同的行为。我需要将 eventData
传递给提供给 toggle()
的处理函数,但似乎只有 .bind()
支持这个,不支持.toggle()
.
我的第一个倾向是使用对单个处理程序函数来说是全局的标志来存储点击状态。换句话说,而不是:
$('a').toggle(function() {
alert('odd number of clicks');
}, function() {
alert('even number of clicks');
});
这样做:
var clicks = true;
$('a').click(function() {
if (clicks) {
alert('odd number of clicks');
clicks = false;
} else {
alert('even number of clicks');
clicks = true;
}
});
我还没有测试后者,但我怀疑它会起作用。这是执行此类操作的最佳方法,还是我缺少更好的方法?
最佳答案
这似乎是一种合理的方式...我只是建议您使用 jQuery 的 data storage实用程序而不是引入额外的变量(如果您想跟踪一大堆链接,这可能会让人头疼)。所以根据你的例子:
$('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);
});
关于javascript - 替代支持 eventData 的 jQuery .toggle() 方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2459153/