HTMLElement.prototype.toggle = function (...args) {
let generator = function* (...args) {
let i = 0;
do {
yield args[i++ % args.length]
} while (true)
};
let iterator = generator(...args);
this.addEventListener('click', () => {
iterator.next().value();
});
};
document.body.toggle(function () {
console.log(1);
}, function () {
console.log(2)
})
要实现jQuery的toggle方法其实不用这么麻烦
Element.prototype.on = function (event, fn) {
try {
this.addEventListener(event, fn);
} catch (e) {
this.attachEvent('on' + event, fn);
}
};
Element.prototype.toggle = function () {
var i = 0;
var args = arguments;
this.on('click', function () {
args[i++ % args.length]();
});
};
document.body.toggle(function () {
console.log(1);
}, function () {
console.log(2)
})