【问题标题】:Pass additional parameters to jQuery each() callback将附加参数传递给 jQuery each() 回调
【发布时间】:2011-06-29 08:44:59
【问题描述】:

我正在开发一款向用户展示调查的应用。标记看起来像这样:

<body>
    <div class="question" id="q1">
        Question 1
    </div>
    <div class="question" id="q2">
        Question 2
    </div>
    <!-- etc -->
</body>

我想使用 jQuery 从 DOM 构造 JavaScript 对象,因此在 Survey 构造函数中,我使用 each() 方法遍历 jQuery 集。问题是在回调函数中,我无法获得对Survey 对象的引用,以便将每个Question 对象附加到Survey.questions 数组中。如何获得对Survey 对象的引用?有没有办法将附加参数(例如对Survey 对象的引用)传递给回调函数?

function Survey() {
    this.questions = new Array;
    $('.question').each(function(i) { (/* Survey object */).questions.push(new Question(this)); });
}

function Question(element) {
    this.element = $(element);
}

【问题讨论】:

    标签: javascript jquery oop


    【解决方案1】:

    您应该能够在迭代问题之前创建对调查的引用。

    function Survey() {
        this.questions = new Array();
        var survey = this;
        $('.question').each(function(i) {
            survey.questions.push(new Question(this));
        });
    }
    
    function Question(element) {
        this.element = $(element);
    }
    
    var survey = new Survey();
    
    $.each(survey.questions, function() {
        $("ul").append("<li>" + this.element.text() + "</li>");
    });
    

    jsfiddle 上的工作示例

    【讨论】:

      【解决方案2】:

      虽然这可能不是相关的答案,但既然问题是如何将参数传递给 jQuery 每个函数。

      第一种方法:使用偏函数 - more on this 来自closure library

      jsfiddle:

      var param = 'extra-param';   
      
      var partial = function(fn, var_args) {
        var args = Array.prototype.slice.call(arguments, 1);
        return function() {
          // Clone the array (with slice()) and append additional arguments
          // to the existing arguments.
          var newArgs = args.slice();
          newArgs.push.apply(newArgs, arguments);
          return fn.apply(this, newArgs);
        };
      };
      
      $(['joe','james','rick','kirk']).each(partial (function (index,value) {
          alert(arguments.length);
          alert(arguments[0]);
       },param));
      

      第二种方法是

      $.each 函数可以带两个参数IndexElement(也可以称为this) 要么 如果您不需要Index,那么您可以将Array 作为参数传递给$.each,元素可以称为this

      注意:args 仅供内部使用 - 由 jQuery 提供

      // Execute a callback for every element in the matched set.
      // (You can seed the arguments with an array of args, but this is
      // only used internally.)
      each: function( callback, args ) {
          return jQuery.each( this, callback, args );
      },
      

      哪个会调用each: function( obj, callback, args )

      如果您将数组作为参数传递,则调用callback.apply( obj[ i ], args ); 否则callback.call( obj[ i ], i, obj[ i ] );

      请注意apply和call的区别

      示例代码:http://jsfiddle.net/dekajp/yA89R/1/

      var param = 'rick';
      $(['joe','james','rick','kirk']).each(function (arg1 , arg2 ,arg3) {
          //alert('[this: '+this +'] [arg1: '+ arg1 +'] [arg2:'+arg2+'] [param:'+param+']');
      },['hello 1','hello 2','hello 3']);
      

      供参考jQuery各代码1.9版

      // args is for internal usage only
          each: function( obj, callback, args ) {
              var value,
                  i = 0,
                  length = obj.length,
                  isArray = isArraylike( obj );
      
              if ( args ) {
                  if ( isArray ) {
                      for ( ; i < length; i++ ) {
                          value = callback.apply( obj[ i ], args );
      
                          if ( value === false ) {
                              break;
                          }
                      }
                  } else {
                      for ( i in obj ) {
                          value = callback.apply( obj[ i ], args );
      
                          if ( value === false ) {
                              break;
                          }
                      }
                  }
      
              // A special, fast, case for the most common use of each
              } else {
                  if ( isArray ) {
                      for ( ; i < length; i++ ) {
                          value = callback.call( obj[ i ], i, obj[ i ] );
      
                          if ( value === false ) {
                              break;
                          }
                      }
                  } else {
                      for ( i in obj ) {
                          value = callback.call( obj[ i ], i, obj[ i ] );
      
                          if ( value === false ) {
                              break;
                          }
                      }
                  }
              }
      
              return obj;
          },
      

      【讨论】:

      • 这个答案是对问题中提出的问题的更彻底的讨论。
      【解决方案3】:

      我遇到了类似的问题。将参数传递给每个函数:

      var param1 = "one";
      var param2 = "two";
      
      var params = [ param1, param2 ];
      
      
      $( '#myTable > tbody  > tr' ).each(function( index ) {
      
           var param1back = params[0];
           var param2back = params[1];
      
      },params);
      

      【讨论】:

      • 为我工作。只是想强调一下,参数应该始终是数组类型。如果 params 是任何其他类型,则不起作用。
      • 这应该是公认的答案,因为它实际上是设计带有 each 之类的方法的 jQuery 参数的方式。其他答案只是过于复杂了。
      • 这不应该是公认的答案。我们可以随心所欲地将变量添加到全局范围,但这只会污染全局空间......这不是好的编码!我认为OP要问的是如何将实例变量传递给.each(),它不会在全局级别定义,因此需要传入。
      • @OleksiiZymovets 对我有用,即使 params 是一个字符串
      【解决方案4】:

      //Create extra data
      var dataArray = ["A", "B", "C"];
      
      //Send default arguments from jQuery's each (index and item) along
      //with our new data argument to a named function handler.
      $("#myList").children().each(function(jqIndex, jqItem)
                                  {
                                    listItemsHandler(jqIndex, jqItem, dataArray[jqIndex]);
                                  });    
      
      //Named function handler accepting 3 arguments.
      function listItemsHandler(index, item, data)
      {
          console.log(index + " " + item + " " + data);
      }
      <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      
      <ol id = "myList">
        <li>First</li>
        <li>Second</li>
        <li>Third</li> 
      </ol>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-03-23
        • 1970-01-01
        • 1970-01-01
        • 2016-02-27
        • 1970-01-01
        • 2019-08-09
        • 2016-09-19
        • 2014-06-14
        相关资源
        最近更新 更多