jQuery deprecated '.toggle()'. Seeking alternative method

匿名 (未验证) 提交于 2019-12-03 03:10:03

问题:

Since .toggle() was deprecated from jQuery, I am looking for a new simple solution which will enable me to create a "Read more" button which slides down a paragraph whilst changing the button text to "Read less".

I have put together this working code:

var moreText = "Read more"; var lessText = "Read less";  $(document).ready(function () {     $("a.readmorebtn").text(moreText);     $("a.readmorebtn").toggle(function () {         $("a.readmorebtn").text(lessText);         $("p.more").slideToggle(0);     },      function () {         $("a.readmorebtn").text(moreText);         $("p.more").slideToggle(0);     }); });

http://jsfiddle.net/approach/gDvyR/

You'll see in the fiddle that 'Migrate 1.1.0' is checked on the options on the left, which is the only way to make .toggle() work in this way with this (newest) version of jQuery.

My question is, can you think of another way of performing the same function but without using .toggle() and Migrate?

Apologies if you feel this question has been answered elsewhere, but I keep finding hints at the workarounds being "relatively straightforward", without really seeing any definitive approaches. Unfortunately being new to jQuery it doesn't seem so straight forward to me!

Many, many thanks.

回答1:

I personally think all the answers here are too elaborate for what you need. This should do the trick just fine and it works with multiple occurences. http://jsfiddle.net/BramVanroy/gDvyR/5/

var moreText = "Read more",     lessText = "Read less",     moreButton = $("a.readmorebtn");  moreButton.click(function () {     var $this = $(this);     $this.text($this.text() == moreText ? lessText : moreText);     $this.next("p.more").slideToggle("fast"); });


回答2:

Here's a generic replacement :

$.fn.toggleFuncs = function() {     var functions = Array.prototype.slice.call(arguments),     _this = this.click(function(){         var i = _this.data('func_count') || 0;         functions[i%functions.length]();         _this.data('func_count', i+1);     }); }

You use it as you would use toggle :

$('something').toggleFuncs(f1, f2, f3);

Demonstration



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!