如何解决在 for 循环中将数组作为函数的参数传递
我试图在 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 看起来像:"<td class="fc-green"><a onclick="showEmployeeDetails([object Object])">1</td>"
最初我试图传递整个 empCatgry2Arr 数组,我使用 map 函数只是为了使用所需的键值。
解决方法
当您呈现 Javascript 时,您的程序必须以与您自己编写代码相同的方式呈现源代码。
将新数组传递给 javascript 函数的方法是将其放在方括号内,并在逗号分隔列表中提供初始值。
var html = 'etc....onclick="ShowEmployeeDetails([' + testArray.join() + '])">' + empCatgry2Count + etc...';
,
像这样创建一个元素并绑定点击事件,我使用了一些模拟数据,点击时你可能会看到控制台日志,它记录了动态传递的数据!
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>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。