简体   繁体   English

在 jquery 中使用 for 循环(.each)

[英]using for loop(.each) in jquery

I have this function notify() with three parameters, user id(number), message, and link.我有这个 function notify() 带有三个参数,用户 ID(号码)、消息和链接。 On the website that I am working on, there are users that are invited to a party by a party host, and I wanna use this notify function to notify only those users that are invited.在我正在开发的网站上,有一些用户被派对主持人邀请参加派对,我想用这个通知 function 只通知那些被邀请的用户。 Every user has their own name and id (in numbers).每个用户都有自己的姓名和 ID(以数字表示)。 But since the user id is a number, how do I use for loop (.each) to notify those users that are invited?但是由于用户 id 是一个数字,我如何使用 for loop (.each) 来通知那些被邀请的用户? For instance, there are 7 users (user 1-7), but only the users 1,3,5 are invited so I want to notify only 1,3, and 5.例如,有 7 个用户(用户 1-7),但只有用户 1、3、5 被邀请,所以我只想通知 1、3 和 5。

PS This is what I have so far, I am so new to JQuery so please help! PS 这是我到目前为止所拥有的,我对 JQuery 很陌生,所以请帮忙!

if ($('#create-party-form').length) { //not sure if it's even right..
        $('#submit-invitation-btn').on('click', function() {
            $('').each(function() { //this is where I am stuck

            })
            notify( ,message, link); //first one should be id# of users that are invited..
        });
    }

Thank you in advance!先感谢您!

I'm not sure how you store the users, but assuming you have an array of user ids who are invited.我不确定您如何存储用户,但假设您有一组被邀请的用户 ID。

const invited = [1, 3, 5];
invited.forEach(id => notify(id, message, link);

This is also not using any jQuery, as you can see it is really simple.这也没有使用任何 jQuery,您可以看到它非常简单。

Or perhaps you store the users like this?或者也许你像这样存储用户?

{
  id: 3,
  name: 'Michael',
  invited: true
}

In that case, you can use filter:在这种情况下,您可以使用过滤器:

users
  .filter(user => user.invited)
  .forEach(user => notify(user.id, message, link)
);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM