在我的 Jquery 插件中执行循环的更好方法?
我在我正在制作的插件中创建了一个 for(var i in obj)
,但我觉得它可以更干净,而不是有一堆 if()
代码> 语句。我正在尝试根据对象项的值创建一个字符串。基本上,如果对象项存在,则将值放入字符串中。希望这是有道理的,如果没有,也许代码会更好地解释它;
以下是我调用插件的方式:
$.aicc('post',{status:'passed'});
或
$.aicc('post',{lesson_location:'1_25 ',status:'通过'});
或
$.aicc('post',{lesson_location:'1_25',status:'passed',score='85'});
它需要是动态的!
代码
(function($)
{
var methods =
{
init:function(p)
{
alert(p);
},
get:function(p)
{
alert(p);
},
post:function(p)
{
var output = '';
for(var i in p)
{
if(i=='lesson_location')
{
output += i+'='+p[i]+'\n';
}
if(i=='status')
{
output += i+'='+p[i]+'\n';
}
alert('[CORE]\n'+output);
}
};
$.aicc = function(method)
{
if(methods[method])
{
return methods[method].apply(this,Array.prototype.slice.call(arguments,1));
}
else if(typeof method==='object'||!method)
{
return methods.init.apply(this,arguments);
}
else
{
$.error('Method ' + method+' does not exist on jQuery.tooltip');
}
};
})(jQuery);
所需输出: "[CORE]\nlesson_location=Page1\ncredit=学分\nscore=85\ntime="00:00:00\nlesson_status=通过"
I've created a for(var i in obj)
in a plugin that I'm making, but I feel like it can be cleaner rather than have a bunch of if()
statements. I am trying to create a string depending on the value of an object item. Basically if the object item is present then put the value in the string. Hopefully that makes sense, if not maybe the code will explain it better;
Here is how I am calling the plugin :
$.aicc('post',{status:'passed'});
or
$.aicc('post',{lesson_location:'1_25',status:'passed'});
or
$.aicc('post',{lesson_location:'1_25',status:'passed',score='85'});
It needs to be dynamic!
Code
(function($)
{
var methods =
{
init:function(p)
{
alert(p);
},
get:function(p)
{
alert(p);
},
post:function(p)
{
var output = '';
for(var i in p)
{
if(i=='lesson_location')
{
output += i+'='+p[i]+'\n';
}
if(i=='status')
{
output += i+'='+p[i]+'\n';
}
alert('[CORE]\n'+output);
}
};
$.aicc = function(method)
{
if(methods[method])
{
return methods[method].apply(this,Array.prototype.slice.call(arguments,1));
}
else if(typeof method==='object'||!method)
{
return methods.init.apply(this,arguments);
}
else
{
$.error('Method ' + method+' does not exist on jQuery.tooltip');
}
};
})(jQuery);
Desired output : "[CORE]\nlesson_location=Page1\ncredit=Credit\nscore=85\ntime="00:00:00\nlesson_status=Passed"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您只需要“打印”对象的键和值,也许以下内容就足够了?
If you just need to 'print out' both keys and values of your object, perhaps the following would suffice?