2017-02-20 5 views
1

У меня есть функция, которая отправляет уведомление на странице, и я предварять основной DIV с уведомлением с, это функция:Div с таким же классом перетаскиваемом

function showNotification_event2(notificationTitle, notificationContent, notificationColor, notificationSize) { 
    console.log('trying to execute notification'); 

    var notificationArea = $('#notification_area'); 
    var notificationHtml; 

    notificationHtml += '<div class="container">'; 
    notificationHtml += '<div class="col-md-' + notificationSize + ' col-centered">'; // column 
    notificationHtml += '<div class="draggable panel panel-pink">'; 
    notificationHtml += '<div class="panel-heading" style="background-color: ' + notificationColor + '">'; 
    notificationHtml += notificationTitle; 
    notificationHtml += '</div>'; 
    notificationHtml += '<div class="panel-body">'; 
    notificationHtml += notificationContent; 
    notificationHtml += '</div>'; 
    notificationHtml += '</div>'; 
    notificationHtml += '</div>'; // end column 
    notificationHtml += '</div>'; 

    $("#notification_area").prepend(notificationHtml); 
    $('.draggable').draggable(); 
} 

Как вы можете видеть, что я объявляю. draggable draggable, но он работает только для первого созданного уведомления, есть ли способ обойти это и сделать все div с этим классом перетаскиваемым?

HTML:

<div id="notification_area"> 
    <!-- Notificiations will automatically be added here. --> 
</div> 

Полный код (немного изменился по сравнению с предыдущим редактирования):

var ws = new WebSocket('ws://localhost:8181/'); 

var hasConnected = false; 

function startWebSockets() { 
    ws.onmessage = function (messageEvent) { 
     onReceiveMessage(messageEvent.data); 
    }; 

    ws.onopen = function() { 
     onConnectionOpened(); 
    }; 

    ws.onclose = function() { 
     onConnectionClosed(); 
    } 
} 

function onReceiveMessage(messageData) { 
    var messageParts = messageData.includes('\\') ? messageData.split('\\') : messageData; 

    if (messageData.includes("\\")) { 
     if (messageParts[0] == "compose:show_custom_notification") { 
      showBootstrapNotification(messageParts[1], messageParts[2], messageParts[3], messageParts[4]); 
     } 
    } 
    else { 
     if (messageData == "compose:authentication_complete") { 
      console.log('Authentication to WebSocket server has been completed.'); 
     } 

     if (messageData == "compose:authentication_failed") { 
      sendMessage("client_identity_token " + habboSso); 
     } 
    } 
} 

function onConnectionOpened() { 
    console.log('Connected to the WebSocket server.'); 
    hasConnected = true; 

    sendMessage("client_identity_token " + habboSso); 
} 

function onConnectionClosed() { 
    if (!hasConnected) { 
     console.log('Failed to connect to the WebSocket server.'); 
    } 
    else { 
     console.log('Your connection to the WebSocket server was unexpectedly closed.'); 
    } 
} 

function sendMessage(message) { 
    if (hasConnected) { 
     ws.send(message); 
    } 
} 

startWebSockets(); 

function showBootstrapNotification(notificationTitle, notificationContent, notificationColor, notificationSize) { 
    console.log('trying to execute notification'); 

    var notificationArea = $('#notification_area'); 
    var notificationHtml; 

    const randomId = '' + new Date().getTime() + '_' + Math.random(); 

    notificationHtml += '<div class="col-md-' + notificationSize + ' col-centered">'; 
    notificationHtml += '<div id="' + randomId + '" class="draggable panel panel-pink">'; 
    notificationHtml += '<div class="panel-heading" style="background-color: ' + notificationColor + '">'; 
    notificationHtml += notificationTitle; 
    notificationHtml += '</div>'; 
    notificationHtml += '<div class="panel-body">'; 
    notificationHtml += notificationContent; 
    notificationHtml += '</div>'; 
    notificationHtml += '</div>'; 
    notificationHtml += '</div>'; 

    $("#notification_area").prepend(notificationHtml); 

    setTimeout(function() { 
     const myToBeDraggableDiv = $('#'+randomId); 
     myToBeDraggableDiv.removeAttr('id'); 
     myToBeDraggableDiv.draggable(); 
    }, 0); 
} 
+1

, когда на самом деле вы обстреливают это событие уведомления, как это может быть ключом. – Ankit

+0

Сложно сказать, что когда я показываю уведомление, когда сервер веб-сервера запрашивает его, но я запускаю его непосредственно через консольное окно Google Chrome, чтобы сэкономить время, отправляющее его во время разработки. – Ashkru

ответ

1

Есть несколько вопросов:

  • Многократно делает один и тот же элемент (s) перетаскиваемый может вызвать проблемы. Вы пробовали выбрать только добавленный новый div div и добавить его в другие перетаскиваемые объекты? (См. Пример)

  • var notificationHtml; < - Этот var является строкой, которая должна быть инициализирована пустой строкой.

  • Существует уже ссылка, созданная для родительского контейнера: var notificationArea = $('#notification_area'); и при добавлении содержимого вы можете использовать эту ссылку. (Не совсем отключающая ошибка)

Фиксация эти ваши функции showBootstrapNotification бы это:

function showBootstrapNotification(notificationTitle, notificationContent, notificationColor, notificationSize) { 
    console.log('trying to execute notification'); 


    var notificationArea = $('#notification_area'); 
    var notificationHtml = ''; 
    notificationHtml += '<div class="col-md-' + notificationSize + ' col-centered">'; 
    notificationHtml += '<div class="draggable panel panel-pink">'; 
    notificationHtml += '<div class="panel-heading" style="background-color: ' + notificationColor + '">'; 
    notificationHtml += notificationTitle; 
    notificationHtml += '</div>'; 
    notificationHtml += '<div class="panel-body">'; 
    notificationHtml += notificationContent; 
    notificationHtml += '</div>'; 
    notificationHtml += '</div>'; 
    notificationHtml += '</div>'; 

    const newNot = $(notificationHtml); 
    notificationArea.prepend(newNot); 
    newNot.draggable(); 
} 
+0

Я попробовал ваш метод и отключил каждое уведомление от перетаскивания. – Ashkru

+0

Предоставьте рабочий образец вашего кода, чтобы мы все могли понять, что случилось. –

+0

Я редактировал свой вопрос с полным .js-файлом. – Ashkru

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