简体   繁体   English

在我的Jquery插件中执行循环的更好方法?

[英]Better way to do a loop in my Jquery plugin?

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. 我在自己制作的插件中创建了for(var i in obj) ,但我觉得它可以更干净,而不是包含一堆if()语句。 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" 所需的输出"[CORE]\\nlesson_location=Page1\\ncredit=Credit\\nscore=85\\ntime="00:00:00\\nlesson_status=Passed"

If you just need to 'print out' both keys and values of your object, perhaps the following would suffice? 如果只需要“打印”对象的键和值,那么下面的内容就足够了吗?

var output = '';
for (var i in p) { 
    output += i + '=' + p[i] + '\n';
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM