这些泛型类如何在不同的div之间区分?

时间:2011-12-15 18:11:31

标签: javascript jquery css

我正在为游戏创建一个通知系统,其工作方式类似于手机中通知的工作方式。

通知都是最初创建的,隐藏的,之后游戏应该从游戏内触发器中“激活”某些通知。

当尝试将通知按类别分开时,我遇到了问题。每个通知都以一个只有标题可见的小矩形框开始。单击后,通知将展开,说明将变为可见。

现在,点击通知会展开该通知并显示其通知,但任何其他通知也会显示其说明。

示例代码:

var NotificationItems = new Array();

scope.registerNotification = function(title, description)
{

    //add it to the array
    NotificationItems.push(new scope.Application(title, description));

    var $NotificationContainer = $("#NotificationContainer");
    $NotificationContainer.append('<div class="Notification" title="'+title+'"></div>');
    var $thisNotification = $NotificationContainer.children('.Notification[title='+title+']');
    $thisNotification.append('<div class="NotificationTitle">'+title+'</div>');
    $thisNotification.append('<div class="NotificationDescription">'+description+'</div>');
    $(".NotificationDescription").hide();

    $thisNotification.click(function()
    {
        $(this).toggleClass('expanded');
        $('.NotificationDescription').slideToggle('slow');
    });
}

如何为每个通知唯一识别.NotificationDescription

3 个答案:

答案 0 :(得分:2)

您可以尝试.children()方法:jQuery docs for children method

$thisNotification.click(function()
{
    $(this).toggleClass('expanded').children('.NotificationDescription').slideToggle('slow');
});

答案 1 :(得分:1)

为找到的元素找到合适的元素:

$thisNotification.click(function()
{
    $(this).toggleClass('expanded');
    $(this).find('.NotificationDescription').slideToggle('slow');
});

如果您愿意,可以将呼叫链接起来:

$thisNotification.click(function()
{
    $(this).toggleClass('expanded').find('.NotificationDescription').slideToggle('slow');
});

答案 2 :(得分:1)

您可能想要尝试事件委派。

$('#NotificationContainer > div.Notification').live('click',function()
{ 
$(this).toggleClass('expanded').find('div.NotificationDescription').slideToggle('slow');
});

这样,您只需要将事件附加一次(在init上),并且单个事件处理所有通知。

您还应该一次添加所有html:

var $NotificationContainer = $("#NotificationContainer");
var $Notification = $('<div class="Notification" title="'+title+'"></div>');
$Notification.append('<div class="NotificationTitle">'+title+'</div>');
$Notification.append('<div class="NotificationDescription">'+description+'</div>');
$NotificationContainer.append($Notification);

注意到细微差别,我们在jquery而不是dom中构建元素,并立即将它们全部附加。