我想知道如何创建jquery函数,然后可以用其中声明的参数名称和值调用jquery函数。
与其按正确的顺序给出这样的函数变量,不如:
myFunction("My function name",true,false);我想发挥这样的作用:
function({
displayName: "My function name",
editable: true,
displayForm: false;
})在参数顺序不重要的地方,因为我给它起了更大的名字。
我在每个jquery (jqPlot、JqGrid、noty等)中都看到了这种配置。下面是一个例子:
$(document).ready(function(){
var plot1 = $.jqplot('chart1', [cosPoints], {
series:[{showMarker:false}],
axes:{
xaxis:{
label:'Angle (radians)'
},
yaxis:{
label:'Cosine'
}
}
});
});-编辑--
我有自己的js函数,可以从json中打印树,但是我有太多的参数,以至于很难阅读和编辑。
发布于 2014-11-26 11:32:04
你没有理由不能做你想做的事情,只是让你的函数期望一个对象文字:
function MyFunction(o){
// Do whatever you need to do with your object properties,
// like set some corresponding scoped variables.
// 0 would be their default values, change as appropriate.
var displayName = o.displayName || 0,
editable = o.editable || 0,
displayForm = o.displayForm || 0;
}那就按你想要的称呼吧:
myFunction({
displayName: "My function name",
editable: true,
displayForm: false;
});为了记录在案,这里没有jQuery功能。这都是香草JavaScript。
注意,如果您使用的是jQuery,那么在使用$.isPlainObject(o)执行功能之前,可以检查该参数实际上是一个对象文本。
发布于 2014-11-26 11:32:04
只需声明以对象为参数的函数:
function myFunction(obj) {
if(obj.displayName) {
// do something with obj.displayName
}
// ....
}你可以按你说的那样称呼它:
myFunction({
displayName: "My function name",
editable: true,
displayForm: false;
});即使是这样:
myFunction({
editable: true,
displayForm: false;
});为了测试作为参数传递的对象中是否存在属性,只需像我所做的那样放置测试:obj.myProperty。
另一点是,您可以在$.extend中放置默认值:
function myFunction(obj) {
var myDefaults = {
displayName: "My default name",
editable: false
};
// Fill `obj` with the missing values that have to be supplied
// and that we take in `myDefaults`
$.extend(obj, myDefaults);
// ...
}发布于 2014-11-26 11:34:27
jQuery扩展
jQuery.fn.extend({
zigzag: function () {
var text = $(this).text();
var zigzagText = '';
var toggle = true; //lower/uppper toggle
$.each(text, function(i, nome) {
zigzagText += (toggle) ? nome.toUpperCase() : nome.toLowerCase();
toggle = (toggle) ? false : true;
});
return zigzagText;
}
});
console.log($('#tagline').zigzag());
//output: #1 jQuErY BlOg fOr yOuR DaIlY NeWs, PlUgInS, tUtS/TiPs & cOdE SnIpPeTs.
//chained example
console.log($('#tagline').zigzag().toLowerCase());
//output: #1 jquery blog for your daily news, plugins, tuts/tips & code snippets.有关更多参考资料,您可以查看:http://www.sitepoint.com/5-ways-declare-functions-jquery/
https://stackoverflow.com/questions/27147994
复制相似问题