jQuery.fn.extend()问题:如何在扩展对象方法中获取匹配元素集合
嘿,这个问题我之前也碰到过,其实有几个实用的解决办法,给你详细说说:
解决方法
方法1:手动传递元素集合作为参数
这是最直接的方式——在testApp方法里,把当前的元素集合(也就是this)作为参数传给InitApp,这样在InitApp里就能直接拿到啦。示例代码如下:
jQuery.fn.extend({ testApp: function() { // 把当前匹配的元素集合传递给InitApp appName.InitApp(this); return this; // 保持jQuery的链式调用特性 } }); var appName = { InitApp: function($targetElements) { // 这里的$targetElements就是你要的class为p1的元素集合 console.log($targetElements); } };
这种方式逻辑清晰,新手也能快速理解,不会搞乱this的指向逻辑。
方法2:用call/apply/bind改变this指向
如果你希望InitApp里的this直接指向元素集合,可以用call、apply或者bind来修改函数的执行上下文。比如用call的示例:
jQuery.fn.extend({ testApp: function() { // 用call把InitApp的this绑定为当前元素集合 appName.InitApp.call(this); return this; } }); var appName = { InitApp: function() { // 现在this就是匹配的元素集合了 console.log(this); // 如果还需要访问appName本身,可以提前存个引用 var appSelf = appName; console.log(appSelf); // 输出appName对象 } };
这种方式适合你想让InitApp的this语义上更贴近元素集合的场景。
方法3:将元素集合挂载到appName对象上
你可以在testApp里把元素集合赋值给appName的一个属性,然后在InitApp里直接访问这个属性:
jQuery.fn.extend({ testApp: function() { appName.$currentElements = this; appName.InitApp(); return this; } }); var appName = { $currentElements: null, InitApp: function() { console.log(this.$currentElements); // 输出目标元素集合 } };
不过要注意,这种方式如果在多个地方同时调用testApp,可能会覆盖$currentElements的值,更适合单实例的场景。
内容的提问来源于stack exchange,提问作者Harun Diluka Heshan
相关产品推荐
相关产品推荐

