Firebase到HTML页面:当数据库中没有值时,如何不打印 "undefined"?

问题描述 投票:1回答:1

我希望我提供所有需要解释我的问题。我完全不擅长脚本,所以原谅我的愚蠢......教我变得更好,请。ˆ

所以你会发现我的脚本在这里。

我想显示所有符合 "今天或未来 "日期的记录。目前进展顺利。

现在有些记录没有艺术家的字段。然后输出是 "未定义"。有没有办法解决这个问题......当值和字段不存在时,不打印任何东西?

    <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>

在这里输入图像描述

javascript html firebase
1个回答
1
投票

你可以使用逻辑 "OR "运算符(写成 "OR")。||)的情况下,有条件地显示其他东西 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.orgen-USdocsWebJavaScriptReferenceOperatorsLogical_Operators。

© www.soinside.com 2019 - 2024. All rights reserved.