首頁  >  文章  >  web前端  >  jquery.proxy的四種使用情境的實例詳解

jquery.proxy的四種使用情境的實例詳解

零下一度
零下一度原創
2017-06-17 17:47:241615瀏覽

其實只有兩種使用方式,只不過每一種又細分是否傳參。

先給一段HTML,後面會用來測試:




#。

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上已經沒有點擊事件,所以再點擊按鈕,也不會有任何反應了。 ######4,jQuery.proxy(context, name [, additionalArguments]);######一個疑問:######請教大家一個問題,#######jQuery.proxy (context, function, params);######與######function.call(context,params);############

以上是jquery.proxy的四種使用情境的實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn