简体   繁体   English

将JQuery数组传递给嵌套函数

[英]Passing JQuery Arrays to Nested Function

I'm having problems with dynamically adding a row to a table using data stored in two arrays ( categories and treatments ). 我在使用存储在两个数组( 类别处理方式 )中的数据向表中动态添加行时遇到问题。 The arrays are fine, I've determined that. 数组很好,我已经确定了。

When passing just the categories array the new row displays but the select box reads [object:object], it's clearly blank. 仅传递类别数组时,将显示新行,但选择框显示为[object:object],显然为空白。

When I pass a second array with it, as shown below, the console reads 'undefined is not a function'. 当我传递第二个数组时,如下所示,控制台显示“未定义不是函数”。

Any help would be hugely appreciated! 任何帮助将不胜感激!

 // Add an extra row when button is clicked
 var counter = 1;
   $('input.add').click(categories, treatments, function(){
      counter++;      

      var newRow = '<tr><td><label for="category' + counter + '">Category</label></td><td><select id="category' + counter + '" name="category' + counter + '" required="required">';      

      $.each(categories, function(key, value) {   
      $('#category' + counter)
         newRow += '<option value ="' + key + '">' + value + '</option>';
      });

      newRow += '</select></td><td><label for="treatment' + counter + '">Treatment</label></td><td><select id="treatment' + counter + '" name="treatment' + counter + '">';

      $.each(treatments, function(key, value) {   
      $('#treatment' + counter)
         newRow += '<option value ="' + key + '">' + value + '</option>';
      });    

      newRow += '</select></td></tr>';     

      $('table.treatments').append(newRow);
   });
});

The first parameter for the jQuery .click() is an Object, and you're trying to pass two arrays. jQuery .click()的第一个参数是一个Object,并且您试图传递两个数组。

This should work for you (remember to check for the missing semi-colons): 这应该为您工作(请记住检查缺少的分号):

// Create an Object obj containing the two arrays.
$('input.add').click(obj = { categories: categories, treatments: treatments }, function () {
    counter++;

    var newRow = '<tr><td><label for="category' + counter + '">Category</label></td><td><select id="category' + counter + '" name="category' + counter + '" required="required">';

    // Use the obj.
    $.each(obj.categories, function (key, value) {
        $('#category' + counter);
        newRow += '<option value ="' + key + '">' + value + '</option>';
    });

    newRow += '</select></td><td><label for="treatment' + counter + '">Treatment</label></td><td><select id="treatment' + counter + '" name="treatment' + counter + '">';

    // Use the obj.
    $.each(obj.treatments, function (key, value) {
        $('#treatment' + counter);
        newRow += '<option value ="' + key + '">' + value + '</option>';
    });

    newRow += '</select></td></tr>';

    $('table.treatments').append(newRow);
});

Demo 演示

jQuery .click() jQuery .click()

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

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