检查元素是否不在数组中以打开窗口

时间:2013-06-11 19:50:40

标签: javascript jquery arrays loops

我在这里做的是与您的在线和离线联系人的某种聊天界面,您可以在窗口拖动。我试图创建一个函数来检查你是否已经打开了一个聊天窗口,以避免重复的窗口。这是我到目前为止的链接。 s2.enigmind.com/jgonzalez/nodeChat我希望你们能看到它。

这是我附加窗口元素的函数,这个函数得到一些我从JSON获得的参数,参数是用户ID名称和状态。

function displayChatWindow(user, status, avatar, id){
    var template = _.template($("#windowTemplate").html(), {userName: user, userStatus: status, userAvatar: avatar, userId: id});
    stackingWidth = stackingWidth - boxWidth;
    /*console.log(stackingWidth);*/
    $("body").prepend(template);
    $(".messages-container").slimScroll({
        height: '200',
        size: '10px',
        position: 'right',
        color: '#535a61',
        alwaysVisible: false,
        distance: '0',
        railVisible: true,
        railColor: '#222',
        railOpacity: 0.3,
        wheelStep: 10,
        disableFadeOut: false,
        start: "bottom"     
    });
    $("#" + id).css({
        top: absoluteY,
        left: stackingWidth
    });
    $("#" + id).find(".minimize").on("click", displayOthersChat);
    $(".chat input, .chat textarea").on("focus", cleanInputs);
    $(".chat input, .chat textarea").on("blur", setInputs);
    addWindow(id, stackingWidth);
}

我在全局范围内拥有的是一个名为var openedWindows = [];的数组,在这个数组中,我使用addWindow函数附加用户ID和位置。

function addWindow(id, offset){
    openedWindows.push({
        id: id,
        offset: offset
    })
}

到目前为止,每次打开一个新窗口时都会将这个添加到数组中,我一直在使用for循环来查看用户和id是否已经在数组中,但我实际上并不知道如何构造我的代码,因为没有办法在第一次检查用户是否在数组中,因为数组是空的,如果你们知道我怎么能实现这一点,我将不胜感激,我知道我的代码不是最好的,这一切都是为了我的学习目的,所以我接受所有的提示!非常感谢你。

1 个答案:

答案 0 :(得分:1)

您已经在使用underscore.js,为什么不使用其_.each()函数来遍历openedWindows中的所有条目:

function addWindow(id, offset) {
    var found = false;

    _.each(openedWindows, function(el, idx) {
        // 'el' is an item in openedWindows, and 'idx' is its position in the array
        if (el.id === id) {
            found = true;
        }
    });

    if (found === false) {
        openedWindows.push({
            id: id,
            offset: offset
        });
    }
}