【问题标题】:Passing an array as a parameter of a function inside a for loop在 for 循环中将数组作为函数的参数传递
【发布时间】:2021-02-01 07:05:14
【问题描述】:

我正在尝试在 for 循环内的 onclick 函数中传递对象数组。数组的范围仅在 for 循环内,所以我不能像 this 那样做。 我的代码示例如下:

for (var j = 0; j < globalVariables.countryColl.length; j++) { 
    var testArray = $.map(empCatgry2Arr, function (e, i) {
                        return {
                            Id: e.ID,
                            company: e.Company,
                            dept: e.Department
                        }
                    });
                    html += "<tr>" +
                        "<td>" + globalVariables.countryColl[j].Title + "</td>" +
                        '<td class="fc-green" onclick="ShowEmployeeDetails(' + testArray + ')">' + empCatgry2Count + '</td>' +
"</tr>";
}
html += "</tbody></table>";
$("#tablediv").append(html);

但是当我检查页面时,HTML 看起来像:"&lt;td class="fc-green"&gt;&lt;a onclick="showEmployeeDetails([object Object])"&gt;1&lt;/td&gt;"

最初我试图传递整个 empCatgry2Arr 数组,我只使用 map 函数来使用所需的键值。

【问题讨论】:

  • 如果你能在 jsFiddle 上添加你的问题就太好了
  • 您希望在 HTML 中呈现什么?您正在将字符串与数组连接起来。您是否期待逗号分隔的列表或其他内容?
  • 这回答了您的问题吗? stackoverflow.com/a/65989148/5236174

标签: javascript jquery arrays datatables


【解决方案1】:

当您渲染 Javascript 时,您的程序必须以与您自己编写代码相同的方式渲染源代码。

将新数组传递给 javascript 函数的方法是将其放在方括号内,并在逗号分隔的列表中提供初始值。

var html = 'etc....onclick="ShowEmployeeDetails([' + testArray.join() + '])">' + empCatgry2Count + etc...';

【讨论】:

    【解决方案2】:

    创建一个元素并像这样绑定点击事件,我使用了一些模拟数据,点击时您可能会看到控制台日志,其中记录了动态传递的数据!

    function ShowEmployeeDetails(param) {
      console.log(param);
    }
    
    const html = $('<table></table>');
    
    for (var j = 0; j < 3; j++) { 
        
        const num = j+1;
        let obj = {"id": num};
    
        const row = $('<tr></tr>').appendTo(html);
        // first td
        $('<td></td>').attr({ class: 'fc-green'}).text("Title" + num).appendTo(row);
    
        // second td    
        const td2 = $('<td></td>').text("ShowEmployeeDetails on click" + num).appendTo(row); 
        
        // bind the click event to the element and then append the element to row
        td2.on('click', ShowEmployeeDetails.bind(null, obj));
        td2.appendTo(row);   
    }
    $("#tablediv").append(html);
    td {
    border: 1px solid;
    padding: 5px;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    <div id="tablediv"></div>

    【讨论】:

      猜你喜欢
      • 2021-01-11
      • 1970-01-01
      • 1970-01-01
      • 2020-04-04
      • 1970-01-01
      • 2011-09-27
      • 2015-10-27
      • 2020-08-12
      • 2018-10-15
      相关资源
      最近更新 更多