[英]Better way to do a loop in my Jquery plugin?
我在自己制作的插件中創建了for(var i in obj)
,但我覺得它可以更干凈,而不是包含一堆if()
語句。 我試圖根據對象項目的值創建一個字符串。 基本上,如果存在對象項,則將值放在字符串中。 希望這是有道理的,如果不是的話,代碼會更好地解釋它;
這是我如何調用插件:
$.aicc('post',{status:'passed'});
要么
$.aicc('post',{lesson_location:'1_25',status:'passed'});
要么
$.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=Credit\\nscore=85\\ntime="00:00:00\\nlesson_status=Passed"
如果只需要“打印”對象的鍵和值,那么下面的內容就足夠了嗎?
var output = '';
for (var i in p) {
output += i + '=' + p[i] + '\n';
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.