简体   繁体   中英

jQuery toggle() method

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.

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

Not recommended. Use .toggleClass() instead

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

Also, why is it not recommended to use?

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:

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.

See further discussion here

因为在jQuery的未来版本中, .toggle()不会在那里供您调用,并且会在代码中出错。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM