将JQuery数组传递给嵌套函数

时间:2014-08-18 17:43:02

标签: javascript jquery arrays

我在使用存储在两个阵列(类别处理)中的数据动态地向表中添加行时遇到问题。阵列很好,我已经确定了。

当只传递categories数组时,新行显示但是选择框显示[object:object],它显然是空白的。

当我传递第二个数组时,如下所示,控制台显示“未定义”不是函数'。

非常感谢任何帮助!

 // 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);
   });
});

1 个答案:

答案 0 :(得分:1)

jQuery .click()的第一个参数是一个Object,你试图传递两个数组。

这应该适合你(记得检查缺少的冒号):

// 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()