我正在研究 jQuery 插件开发,我想链接方法。我在 jQuery 教程 ( https://learn.jquery.com/plugins/basic-plugin-creation/ ) 中读到,您可以通过将 return this;
添加到方法的末尾来链接方法,这适用于第一个方法(测试 1)。对于使用 console.log
的第二种方法(测试 2),我该如何做到这一点?所有方法都可以链接吗?
// test 1
$.fn.greenify = function () {
this.css('color', 'green');
return this;
};
// test 2
$.fn.console = function () {
this.on('click', function () {
console.log('hello world');
});
};
$('a').greenify().console();
最佳答案
第二个方法应该返回 jQuery 实例。事件处理程序使用 console.log
函数这一事实与该方法的返回值无关。当 on
返回您可以编码的 jQuery 对象时:
$.fn.console = function () {
return this.on('click', function () {
console.log('hello world');
});
};
现在 console
方法是可链接的!
关于JavaScript/jQuery : How to Chain a Method that uses console. 日志(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30157097/