2012-06-30 5 views
0

Вот мой код:Родители JQuery(). Eq (2) и .parent(). Parent() не ведут себя?

function showNotification(title, message) { 
    var newNotification = $('<div></div>'); 
    var newNotificationHeader = $('<div>' + title + '</div>'); 
    var newNotificationCloser = $('<div></div>'); 
    newNotificationCloser.click(function(){ 
     closeNotification($(this).closest('notification')); 
    }); 
    var newNotificationMessage = $('<div>' + message + '</div>'); 

    newNotification.attr('class', 'notification'); 
    newNotification.css('opacity', 0); 
    newNotificationHeader.attr('class', 'notificationHeader'); 
    newNotificationCloser.attr('class', 'notificationCloser'); 


    newNotificationMessage.attr('class', 'notificationMessage'); 

    newNotificationHeader.append(newNotificationCloser); 
    newNotification.append(newNotificationHeader); 
    newNotification.append(newNotificationMessage); 

    $('body').append(newNotification); 
    newNotification.animate({left: '10px', opacity:1}, 400).delay(15000).animate({top: '61px', opacity:0}, 500); 

} 

function closeNotification(notificationWindow) { 
    notificationWindow.animate({top: '61px', opacity:0}, 500); 
} 

В основном я пытаюсь гнездится несколько див, а затем добавить их к телу.

Функция closeNotification() ожидает основного div с классом «уведомление». Я не могу использовать идентификаторы, потому что в любой момент может быть несколько уведомлений на странице.

<body> 
    <div class="notification"> 
     <div class="notificationHeader"> 
      <div class="notificationCloser"> 
      </div> 
     </div> 
     <div class="notificationMessage"> 
     </div> 
    </div> 
</body> 

Я пытался использовать следующие два метода в коде щелкните на notificationCloser в:

closeNotification($(this).parent().parent()); 

и

closeNotification($(this).parents().eq(1)); 

Как ни странно это, кажется, не работает, но следующие будут скрыть корпус:

closeNotification($(this).parent().parent().parent()); 

и

closeNotification($(this).parents().eq(2)); 

Любая помощь по этому вопросу будет оценена по достоинству.

+1

Вы знаете, что есть метод jQuery для добавления классов? ['addClass()'] (http://api.jquery.com/addClass/) – elclanrs

ответ

1

Быстрый ответ: используйте .closest('.notification') вместо .parent().

Но я хотел бы предложить вам другой подход. Использование шаблона упростит и упростит ваш код.

Один простой способ сделать их, чтобы обернуть их в тег сценария (с неизвестным типом, поэтому он игнорируется)

<body> 
    <script type="text/template" id="notification-template"> 
     <div class="notification"> 
      <div class="header"> 
       <div class="close"></div> 
      </div> 
      <div class="message"></div> 
     </div> 
    </script> 
</body> 

(который работает во всех браузерах, но если вы не устраивает это вы можете просто бросить div.notification элемент на странице с display:none и клонировать его)

а затем мы создаем функцию конструктора для объектов уведомления:

function Notification(title, message){ 
    // create new DOM element based on the template 
    var el = this.el = $(Notification.template); 
    el.find('.header').text(title); 
    el.find('.message').text(message); 
    // close event handler, make sure `this` inside 
    // the 'hide' function points to this Notification object 
    el.find('.close').click($.proxy(this.hide, this)); 
} 

// save the template code here once 
Notification.template = $('#notification-template').text(); 

// methods 
Notification.prototype = { 
    show: function(){ 
     this.el.appendTo(document.body); 
    }, 
    hide: function(){ 
     this.el.remove(); 
    } 
}; 

Который может использоваться следующим образом:

var bacon_warning = new Notification("Out of bacon", "You've ran out of bacon"); 
bacon_warning.show(); 
+0

Спасибо Рикардо, но теперь я думаю, что проблема связана с моим анимированным – CEOofOGN

+0

@ user1462511 с этим решением, вам просто понадобится 'setTimeout ($ .proxy (this.hide, this), 10000) ':) –

+0

Я ценю это, но я также собираюсь соблюдать соответствие HTML5. Я не могу иметь теги скриптов в теле. Этот код будет в .js-файле и включен в голову. – CEOofOGN

Смежные вопросы