2016-01-08 37 views
0
var widescreen = { 
    "flex": "0 100%", 
    "width": "100%", 
    "-webkit-flex": "0 100%", 
    "-moz-flex": "0 100%", 
    "-ms-flex": "0 100%", 
}; 

jQuery.fn.MonPlugin=function() { 
jQuery(".size-60").css(widescreen) 
}; 

jQuery(".titre1").bind("click",MonPlugin); 

我想使用MonPlugin作爲函數,我包含在不同的事件,但控制檯返回未捕獲的ReferenceError:未定義MonPlugin。jquery myfunction沒有定義

回答

0

var widescreen = { 
 
    "flex": "0 100%", 
 
    "width": "100%", 
 
    "-webkit-flex": "0 100%", 
 
    "-moz-flex": "0 100%", 
 
    "-ms-flex": "0 100%", 
 
}; 
 

 
// a plugin declared like this is added to jQueryies prototype allowing 
 
// you to add the method to the chain of functions. but you would need to modify 
 
// your code just a tad. 
 

 
jQuery.fn.MonPlugin = function() { 
 
    // plugins have the collection of the selected elements so loop through them all 
 
    this.each(function(){ 
 
    // create a new jQuery object with the current element and bind your function 
 
    jQuery(this).on('click', MonPluginCallBack); 
 
}; 
 

 
// to call your plugin you would use 
 
jQuery('.titre1').MonPlugin(); 
 

 

 
// it seems that you just want a callback function so you should use 
 

 
function MonPluginCallBack(event){ 
 
    jQuery(".size-60").css(widescreen); 
 
} 
 

 
// here you are passing the function by reference 
 
jQuery(".titre1").bind("click", MonPluginCallBack);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

+0

謝謝,如果我想重置的CSS(標準值是60%),則推薦該方法?謝謝 – Laurent

+0

如果你有權訪問CSS文件,我會做所有的CSS那裏,並簡單地切換與JavaScript類來觸發不同的狀態。如果你沒有訪問CSS,你應該在父狀態下保存一個變量 – synthet1c

1

而是使用這種方式創建功能:

var MonPlugin = function() { 
    jQuery(".size-60").css(widescreen) 
}; 

function MonPlugin() { 
    jQuery(".size-60").css(widescreen) 
} 
3

呼叫

jQuery(".titre1").bind("click",$.fn.MonPlugin); 

,而不是

jQuery(".titre1").bind("click",MonPlugin); 
0

customjqueryfunctionjqueryfunctionextenders只能與jquery object使用。所以爲了調用一個自定義函數,你需要把它附加到一個元素上。

$.fn.MonPlugin = function() 
{ 
    alert(); 
} 

$(".titre1").bind("click",function() 
{ 
    $(this).MonPlugin(); 
}) 

實施例:http://jsfiddle.net/DinoMyte/bvtngh57/149/