jQuery toggle()方法 [英] jQuery toggle() method

查看:41
本文介绍了jQuery toggle()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如我现在所知道的那样.toggle()方法在jQuery 1.9版中已被弃用.可以,但是我很熟悉.解决方案是导入最新的jQuery迁移插件.

As I know now .toggle() method is deprecated in jQuery version 1.9. It is ok, but I was familiar with it. The solution was to import the latest jQuery migrate plugin.

在官方jQuery API文档上,我可以看到.toggle()方法的描述中有一条注释:

On the official jQuery API documentation I can see that there is a note in the description of the .toggle() method:

不推荐.改用.toggleClass()

Not recommended. Use .toggleClass() instead

是的,我可以改用.toggleClass(),但是在这种情况下,它只能在两个类之间切换.

Yes, I may use .toggleClass() instead, but in this case it only switches between two classes.

此外,为什么不建议使用?

Also, why is it not recommended to use?

推荐答案

不推荐使用.改用.toggleClass()"注释与所提供的示例有关,该示例使用.toggle()切换类,不是一般注释关于.toggle().

The "Not recommended. Use .toggleClass() instead" comment is about the provided example, which toggles a class using .toggle(), it's not a general comment about .toggle().

文档还说明了不建议使用的原因:

The docs also state why it is not recommended to use:

为方便起见,提供了.toggle()方法.相对来说 可以直接手动实现相同的行为,并且这可以 如果内置于.toggle()的假设证明是限制性的,则有必要. 例如,如果应用.toggle(),则不能保证其正常工作 两次到同一个元素.由于.toggle()内部使用点击 处理程序来完成其工作,我们必须取消绑定点击才能删除行为 附加了.toggle(),因此其他点击处理程序可以在 交火.该实现还会在上调用.preventDefault() 事件,因此不会关注链接,也不会单击按钮 如果已在元素上调用.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. For example, .toggle() is not guaranteed to work correctly if applied twice to the same element. Since .toggle() internally uses a click handler to do its work, we must unbind click to remove a behavior attached with .toggle(), so other click handlers can be caught in the crossfire. The implementation also calls .preventDefault() on the event, so links will not be followed and buttons will not be clicked if .toggle() has been called on the element.

在此处查看更多讨论

这篇关于jQuery toggle()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆