1

我开始学习 Jquery,但在理解函数参数时遇到了麻烦:(如果您查看我的第一个代码并运行它:我的脚本将起作用 (没有参数)。如果您查看我的第二个代码
(有参数)并运行它:第二个脚本也可以 工作!!

我的第一个问题:我是否在第二个脚本中正确设置了参数
第二个问题:我如何检查我的参数设置或是否 正确传递给我的函数?
PS 抱歉,我很抱歉,谢谢!

   //First code (WITHOUT PARAMETERS!!!) 
   $(document).ready(function () {
       var addclass = $('p:first');

       function AddClass() {
           addclass.addClass('first');
           if (addclass.is($('.first'))) {
               alert('here');
           }
           else {
               alert('not here');
           }
       }
       $('.button').click(function () {
           AddClass(addclass);
       });
   });
   //Second code (WITH PARAMETERS)
   $(document).ready(function () {
       var addclass = $('p:first');

       function AddClass(addclass) {
           addclass.addClass('first');
           if (addclass.is($('.first'))) {
               alert('here');
           }
           else {
               alert('not here');
           }
       }
       $('.button').click(function () {
           AddClass(addclass);
       });
   });
4

2 回答 2

2

您的第二个参数是正确的,并且要检查传递给函数的任何参数,请使用:

arguments.length

例如:

function myfunc() {
   alert( arguments.length ); //output: 1, because you passed one argument

   // and to get that

   var myarg = arguments[0];
}

myfunc(someVar);

如果您不传递任何参数,则:

function myfunc() {
   alert( arguments.length ); //output: 0, because you passed no argument
}

myfunc();

对于您的功能:

  function AddClass(addclass) {

                      ^-- declaring addclass is not necessary if you use like following

       // checking for argument

       if( arguments.length ) {
         // arguments[0] will give you addclass
         // you may not write addclass to function like above
       }

       addclass.addClass('first');
       if (addclass.is($('.first'))) {
           alert('here');
       }
       else {
           alert('not here');
       }
   }

带参数调用函数addclass

   $('.button').click(function () {
       AddClass(addclass);
   });
于 2012-07-02T16:05:38.920 回答
0

Yes you passed correctly the arguments to your second function, to see the arguments passed to your function can see them in two ways:

individually using the array notation

function AddClass(addClass) {
    console.log(arguments[0]); // This will show you the first parameter
    // Some code...
}

With the jQuery function $.each();

function AddClass(addClass) {
    $.each(arguments, function (key, value) {
        console.log(value); // Output the value of all of your arguments
    });
}

In this case don't matter if you pass or not the parameters because the addClass variable that you access and modify in the function AddClass are in the same scope.

You should take a look to this post JavaScriptVariableScope to understand what is happening in your actual code and why your two samples of code works properly.

于 2012-07-02T16:30:14.707 回答