可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I'm using trying to use mootools for a quick task of toggling some text on click. But I can't seem to find a Mootools equivalent of jQuery's toggle() function.
What I'm trying to do is as follows:
$('a#id').toggle( function() { $(this).set('html', 'new text'); }, function() { $(this).set('html', 'old text'); } );
How would I modify the above code for mootools?
Thanks!
回答1:
As far as I know that "toggle" on mootools doesn't exists.
You could "implement" it, by this way for example: http://www.jsfiddle.net/steweb/rdvx8/
Is this what you'd like to obtain?
Edit (for mootools developers :D ), this could be a way to create a general "toggle":
Element.implement({ toggle: function(fn1,fn2){ this.store('toggled',false); return this.addEvent('click',function(event){ event.stop(); if(this.retrieve('toggled')){ fn1.call(this); }else{ fn2.call(this); } this.store('toggled',!(this.retrieve('toggled'))); }); } }); //using it in a 'jQuery' mode $('mya').toggle( function() { this.set('html', 'new text'); }, function() { this.set('html', 'old text'); } );
fiddle here: http://www.jsfiddle.net/steweb/qBZ47/
edit 2 check out an improved version http://jsfiddle.net/dimitar/UZRx5/ (thanks @Dimitar Christoff)
回答2:
i know you accepted the other answer but mootools 1.3 now provides an excellent new feature, Element Pseudos which I feel will be a good solution here. for starters, code below
http://www.jsfiddle.net/dimitar/VR9k8/4/
(function() { var toggled = 0; Event.definePseudo('toggle', function(split, funcsArray, args){ if (funcsArray.length && funcsArray[toggled]) funcsArray[toggled].apply(this, args); // args[0] is the Event instance toggled++; if (toggled >= funcsArray.length) toggled = 0; }); })(); document.id("foo").addEvent("click:toggle", [function(e) { e.stop(); alert("function 1"); }, function(e) { e.stop(); alert("function 2"); }, function(e) { e.stop(); // event object (args[0]) console.dir(e); alert("function 3"); }]);
...will allow you to daisy chain nn number of functions to loop-run consecutively as well as passing on arguments or at least the original event.
docs: http://mootools.net/docs/more/Element/Element.Event.Pseudos
the equivalent or improved version of the element prototype solution is here