简体   繁体   中英

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. 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"

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';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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