jQuery .each() 与数组
基本上,我试图收集具有特定类的每个元素的 ID,并将这些 ID 放入一个数组中。我正在使用 jQuery 1.4.1 并尝试使用 .each(),但并不真正理解它或如何将数组传递出函数。
$('a#submitarray').click(function(){
var datearray = new Array();
$('.selected').each(function(){
datearray.push($(this).attr('id'));
});
// AJAX code to send datearray to process.php file
});
我确信我还很遥远,因为我对此很陌生,所以任何建议帮助都会很棒。谢谢!
Basically, I am trying to gather the IDs of every element with a specific class and place those IDs into an array. I'm using jQuery 1.4.1 and have tried using .each(), but don't really understand it or how to pass the array out of the function.
$('a#submitarray').click(function(){
var datearray = new Array();
$('.selected').each(function(){
datearray.push($(this).attr('id'));
});
// AJAX code to send datearray to process.php file
});
I'm sure I'm way off, as I'm pretty new at this, so any advice help would be awesome. Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
您也可以使用
map()
:map()
方法将每个索引(我的示例未使用)和元素传递到给定函数中,并构建一个数组从返回值中为您提供。You can use
map()
too:The
map()
method passes each index (which my example doesn't use) and element into the given function, and builds an array for you from the return values.尝试使用 jquery 的
map
函数:Try with jquery's
map
function:您不必将数组传递给匿名函数,因为它位于同一作用域中。
You don't have to pass on the array to the anonymous function because it lives in the same scope.
基于其他答案,这里是一个简化版本:
map 函数从每个元素获取 id ,并且 get 函数返回一个数组。在传递给
map
的匿名函数中,this
依次引用每个选定的元素。Building on the other answers, here is a simplified version:
The map function gets the id from each element, and the get function returns an array. Within the anonymous function passed to
map
,this
refers to to each selected element in turn.对我来说一切看起来都很好,该数组将被填充并在您放置评论的地方可用。对自己有信心。
IT all looks good to me, the array will be populated and be available where you have placed the comment. Have faith in yourself.
应该加载数组;您可以使用
jQuery.post
将其发送到服务器。 ..The array should be loaded; you can send it to the server using
jQuery.post
...