javascript - Foreach 循环 javascript 失败

标签 javascript jquery

为什么这个 each 语句会导致我的代码中断?我还必须使用 javascript 设置索引吗?

var email = [];

email['update'] = true;
email['e_case_id'] = $("#e_case").val();

var i = 0;

$.each($('.rowChecked'), function() {
    email['e_attachments'][i] = $(this).attr('id');
    i++;
});

最佳答案

首先,email 应该是对象字面量,而不是数组字面量:

var email = {};

其次,您在尝试使用 email['e_attachments'] 之前没有定义它。这可能是阻止它工作的原因。尝试添加

email['e_attachments'] = [];

$.each 之前。


您可以使用 $.map在这种情况下,顺便说一句。即:

email['e_attachments'] = $.map($('.rowChecked'), function (el) { 
    return $(el).attr('id'); 
});

而不是你的$.each。或者更好:

email['e_attachments'] = $('.rowChecked').map(function () { 
    return $(this).attr('id'); 
}

关于javascript - Foreach 循环 javascript 失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16552205/

相关文章:

javascript - 如何根据 iframe 大小调整引导模式的大小?

javascript - 从jquery数组中删除匹配的元素

javascript - 如何过滤整个JSON对象?

javascript - 使用爬虫查找多个网站的字体系列

jquery - 为什么在 IE7 中使用 jquery 1.8.3 的 offset 时出现语法错误

javascript - 我应该创建一个标量/数字类来防止浮点错误吗?

javascript - PHP/HTML 提交后记住所选值 - 从 MySQL 填充的选项

javascript - 在 Jquery 中创建元素

jquery - 像 jQuery 一样处理 Angular 4 中 html 元素的点击?

jquery - 调整位置 :Fixed div to make it responsive/fluid 的宽度