Firebase to HTML page: как не печатать undefined, если в базе данных нет значения - PullRequest
1 голос
/ 28 мая 2020

Надеюсь, я предоставлю все необходимое для объяснения моей проблемы. Я совсем не умею писать сценарии, так что простите мне мою глупость ... научите меня поправляться, пожалуйста. ˆˆ

Итак, вы найдете здесь мой сценарий.

Я хочу показать все записи, которые соответствуют дате «сегодня или в будущем». Пока все идет хорошо.

Сейчас на некоторых записях нет полевых исполнителей. И тогда вывод будет «undefined». Есть ли способ скрыть это ... просто не печатать ничего, когда значение и поле отсутствуют?

    <script src="https://www.gstatic.com/firebasejs/7.2.0/firebase.js"></script>


    <script>
    // Set the configuration for your app

    var config = {
      apiKey: "xxx",
      authDomain: "xxx",
      databaseURL: "xxx",
      storageBucket: "xxx"
      };
      firebase.initializeApp(config);

    // Get a reference to the database service

    //var db = firebase.database();
    const preObject = document.getElementById('Agenda');
    const ulList = document.getElementById('AgendaList');

    // Create references

    const dbRefObject = firebase.database().ref().child('Event');

    // Synch object changes

    dbRefObject.orderByChild("Date").startAt(new Date().toISOString().slice(0,10)).on('child_added', snap => {

    var data = [];
    const li = document.createElement('li');
    var JSONValue = snap.val();

    // create a variable that checks wheater or not there is a picture. If there is a picture print the picture if not do not print anything
    var photo = "";
    if (JSONValue['Photo']!==undefined) {
      photo='<img class="photo" src="'+JSONValue['Photo']+'">'; 
    }

    // check the value of the status field. If the status is Cancelled, print the status. else do not print anything
    var status = ""; 
    if (JSONValue['Status']==='Geannuleerd') {
      status='<span class="status">'+JSONValue['Status']+'</span>';
    }

    // check the value of the message field. If the message is nieuwsbericht then do not print the date. Else print the date.
    var date = "";
    if (JSONValue['Message']==='Concert') {
      date=JSONValue['FullDate'] + '-' + JSONValue['ShortTime']; 
    }

    // check the value of the message field. If the message is nieuwsbericht then do not print the date. Else print the date.
    var title = "";
    if (JSONValue['Message']==='Concert') {
      title=JSONValue['Concert']; 
    }   

    li.innerHTML = '<div class="event">'+photo+'<h3>' +date+ '</h3>' + '<h1>' +title+ '</h1>' + JSONValue['Artists'] + '</div>';
    li.id = snap.key;
    ulList.appendChild(li);

    });
    </script>

введите здесь описание изображения

1 Ответ

1 голос
/ 28 мая 2020

Вы можете использовать логический оператор «ИЛИ» (записанный как ||) для условного отображения чего-то еще в случае, если JSONValue['Artists'] не определено.

JSONValue['Artists'] || ""

Это в основном означает «получить значение JSONValue['Artists'], или если его значение является ложным (undefined, null, empty, zero, false), используйте вместо "пустую строку".

Соответствующая строка в вашем коде будет:

li.innerHTML = '<div class="event">'+photo+'<h3>' +date+ '</h3>' + '<h1>' +title+ '</h1>' + (JSONValue['Artists'] || "") + '</div>';

Я добавил круглые скобки вокруг JSONValue['Artists'] || "", чтобы сделать порядок операций явным.

Вы также можете использовать что-то еще в качестве запасного варианта:

JSONValue['Artists'] || "No artists for this concert"

Вы можете узнать больше о логических операторах здесь: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators

...