摘要:本文讲解了jQuery.proxy的3种使用场景,希望阅读本篇文章以后大家有所收获,帮助大家对jQuery.proxy的理解更加深入。
其实只有两种使用方式,只不过每一种又细分是否传参。
先给一段HTML,后面会用来测试:
<p><button id=”test”>Test</button></p> <p id=”log”></p>
1,jquery.proxy(function, context);
使用context作为function运行上下文(即this)
2,jQuery.proxy(function, context [, additionalArguments]);
传递参数给function
使用场景:click时,执行function,在给定的context里,同时传递两个参数,如果需要event,则可以作为function第三个参数。
注意:function执行的环境如果不适用proxy,则context会是当前点击对象,现在指定了其他的上下文,已经跟当前点击对象没有一点关系了。
var me = { /* I'm a dog */ type: "dog", /* Note that event comes *after* one and two */ test: function(one, two, event) { $("#log") /* `one` 是第一个附加参数,与对象`you`对应 */ .append( "<h3>Hello " + one.type + ":</h3>" ) /* `two` 是第二个附加参数,与对象`they`对应 */ .append( "and they are " + two.type + ".<br>" ) /* `this` 是上下文,与普通对象`me`对应 */ .append( "I am a " + this.type + ", " ) /* 事件类型是点击"click" */ .append( "Thanks for " + event.type + "ing " ) /* `event.target`是被点击元素,类型是按钮button */ .append( "the " + event.target.type + "." ); } }; var you = { type: "cat" }; var they = { type: "fish" }; /* 一共4个参数:第一个是function,第二个是context,第三、四是参数 */ var proxy = $.proxy( me.test, me, you, they ); $("#test").on( "click", proxy ); /* 运行结果: Hello cat: and they are fish. I am a dog, Thanks for clicking the submit. */
在这种情况下,click仅仅相当于一个触发按钮,触发后执行的函数,跟click一点关系都没有了。
3,jQuery.proxy(context, name);
使用场景:context是一个PlainObject,name是其方法。在click时执行,但test函数执行的上下文是obj,不是$(“#test”)
var obj = { name: "John", test: function() { console.log(this); $("#log").append( this.name ); $("#test").off("click", obj.test); } };
$("#test").on( "click", jQuery.proxy( obj, "test" ) );//在click时执行,但又
不是click的上下文
结果分析:在绑定点击事件后,第一次执行时,就把该绑定去除了。
去除之后,button上已经没有点击事件,所以再点击按钮,也不会有任何反应了。
本文由职坐标整理并发布,希望对同学们有所帮助。了解更多详情请关注职坐标WEB前端jQuery频道!
您输入的评论内容中包含违禁敏感词
我知道了
请输入正确的手机号码
请输入正确的验证码
您今天的短信下发次数太多了,明天再试试吧!
我们会在第一时间安排职业规划师联系您!
您也可以联系我们的职业规划师咨询:
版权所有 职坐标-一站式IT培训就业服务领导者 沪ICP备13042190号-4
上海海同信息科技有限公司 Copyright ©2015 www.zhizuobiao.com,All Rights Reserved.
沪公网安备 31011502005948号