使用javascript添加基于json值的动态div标签

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用javascript添加基于json值的动态div标签相关的知识,希望对你有一定的参考价值。

enter image description here我有一个div标签,我正在动态添加一组p标签,它将从json获取值。问题是p标签被添加到同一个div而不是在单个box中打印。下面是我所拥有的代码试图实现逻辑。价格标签单独打印在同一个div中,而其他标签没有显示。

window.onload = function() {
   document.getElementById('returnDate').style.display = 'none';
   document.getElementsByClassName("flightDetails")[0].style.display = "none";
   flightDetails = [{
           "airline": "H-200",
           "from": "Bangaluru(BLR)",
           "to": "Delhi(DEL)",
           "detail": [{
               "FlightNum": "H-201",
               "date": "2019-12-30",
               "price": "3900",
               "departTime": "12:00 PM",
               "arriveTime": "14:00 PM",
               "seats": "10"
           }, {
               "FlightNum": "H-202",
               "date": "2019-12-31",
               "price": "3000",
               "departTime": "17:30 PM",
               "arriveTime": "19:30 PM",
               "seats": "3"
           }, {
               "FlightNum": "H-203",
               "date": "2019-06-01",
               "price": "2100",
               "departTime": "09:00 AM",
               "arriveTime": "11:00 AM",
               "seats": "7"
           }]
       }, {
           "airline": "K-200",
           "from": "Delhi(DEL)",
           "to": "Bangaluru(BLR)",
           "detail": [{
               "FlightNum": "K-201",
               "date": "2019-12-30",
               "price": "3000",
               "departTime": "12:00 PM",
               "arriveTime": "14:00 PM",
               "seats": "10"
           }, {
               "FlightNum": "K-202",
               "date": "2019-12-31",
               "price": "3000",
               "departTime": "17:30 PM",
               "arriveTime": "19:30 PM",
               "seats": "3"
           }, {
               "FlightNum": "K-203",
               "date": "2019-06-01",
               "price": "2100",
               "departTime": "09:00 AM",
               "arriveTime": "11:00 AM",
               "seats": "7"
           }]
       },
       {
           "airline": "B-200",
           "from": "Chennai(CHN)",
           "to": "Goa(GOA)",
           "detail": [{
               "FlightNum": "B-201",
               "date": "2019-12-30",
               "price": "4000",
               "departTime": "12:00 PM",
               "arriveTime": "14:00 PM",
               "seats": "20"
           }, {
               "FlightNum": "B-202",
               "date": "2019-12-31",
               "price": "3000",
               "departTime": "17:30 PM",
               "arriveTime": "19:30 PM",
               "seats": "3"
           }, {
               "FlightNum": "B-203",
               "date": "2019-06-01",
               "price": "2100",
               "departTime": "09:00 AM",
               "arriveTime": "11:00 AM",
               "seats": "7"
           }]
       },
       {
           "airline": "A-201",
           "from": "Chennai(CHN)",
           "to": "Delhi(DEL)",
           "detail": [{
               "FlightNum": "A-202",
               "date": "2019-12-30",
               "price": "3900",
               "departTime": "12:00 PM",
               "arriveTime": "14:00 PM",
               "seats": "10"
           }, {
               "FlightNum": "A-203",
               "date": "2019-12-31",
               "price": "3000",
               "departTime": "17:30 PM",
               "arriveTime": "19:30 PM",
               "seats": "3"
           }, {
               "FlightNum": "A-204",
               "date": "2019-06-01",
               "price": "2100",
               "departTime": "09:00 AM",
               "arriveTime": "11:00 AM",
               "seats": "7"
           }]
       }, {
           "airline": "A-301",
           "from": "Delhi(DEL)",
           "to": "Hydrabad(HYD)",
           "detail": [{
               "FlightNum": "A-302",
               "date": "2019-05-30",
               "price": "3900",
               "departTime": "08:10 AM",
               "arriveTime": "10:10 AM",
               "seats": "5"
           }, {
               "FlightNum": "A-303",
               "date": "2019-05-30",
               "price": "3000",
               "departTime": "15:45 PM",
               "arriveTime": "17:45 PM",
               "seats": "1"
           }, {
               "FlightNum": "A-304",
               "date": "2019-06-01",
               "price": "2190",
               "departTime": "19:20 PM",
               "arriveTime": "21:20 PM",
               "seats": "12"
           }]
       }, {
           "airline": "A-401",
           "from": "Calicut(CAL)",
           "to": "Delhi(DEL)",
           "detail": [{
               "FlightNum": "A-402",
               "date": "2019-05-30",
               "price": "3000",
               "departTime": "09:00 AM",
               "arriveTime": "10:50 AM",
               "seats": "3"
           }, {
               "FlightNum": "A-403",
               "date": "2019-05-30",
               "price": "2910",
               "departTime": "14:00 PM",
               "arriveTime": "15:50 PM",
               "seats": "5"
           }, {
               "FlightNum": "A-404",
               "date": "2019-06-01",
               "price": "3180",
               "departTime": "21:10 AM",
               "arriveTime": "23:00 AM",
               "seats": "12"
           }]
       }, {
           "airline": "J-500",
           "from": "Delhi(DEL)",
           "to": "Chennai(CHN)",
           "detail": [{
               "FlightNum": "J-502",
               "date": "2019-05-30",
               "price": "2820",
               "departTime": "07:50 AM",
               "arriveTime": "09:40 AM",
               "seats": "7"
           }, {
               "FlightNum": "J-503",
               "date": "2019-05-30",
               "price": "2901",
               "departTime": "11:00 AM",
               "arriveTime": "13:10 PM",
               "seats": "21"
           }, {
               "FlightNum": "J-504",
               "date": "2019-06-01",
               "price": "3000",
               "departTime": "15:20 PM",
               "arriveTime": "17:10 PM",
               "seats": "3"
           }]
       }
   ];
   inputOrigin = document.getElementById('origin');
   inputDesination = document.getElementById("desination");
   originOptions = document.getElementById('originCountry');
   destinationOptions = document.getElementById('desinationCountry');

   var originCategories = new Set();
   var destinationCategories = new Set();

   flightDetails.forEach((o) => originCategories.add(o.from));
   originCategories = [...originCategories];

   flightDetails.forEach((o) => destinationCategories.add(o.to));
   destinationCategories = [...destinationCategories];


   for (i = 0; i < originCategories.length; i++) {
       originOptions.innerhtml += ' <option>' + originCategories[i] + '<option>';
   }

   for (i = 0; i < destinationCategories.length; i++) {
       destinationOptions.innerHTML += ' <option>' + destinationCategories[i] + '<option>';
   }

}

function searchFlights() {
   document.getElementsByClassName("searchResultsHeader")[0].style.borderBottom = "1px solid #ccc;";
   var orginVal, onewayVal, destinationVal, departureVal, returnDateVal, passengersVal, ErrorMessage;
   ErrorMessage = document.getElementById("errorMsg");
   onewayVal = document.getElementById("oneWay").value;
   orginVal = document.getElementById("origin").value;
   destinationVal = document.getElementById("desination").value;
   departureVal = document.getElementById("departureDate").value;
   returnDateVal = document.getElementById("returnDate").value;
   passengersVal = document.getElementById("passengers").value;
   try {
       if (orginVal === "" || onewayVal === "" || destinationVal === "" || departureVal === "" || passengersVal === "") {
           throw "Please fill all the details";
       } else if (orginVal === undefined || destinationVal === undefined) {
           throw "Please select Valid origin and destination."
       } else if (destinationVal === orginVal) {
           throw "Please select different origin and destination."
       } else {

           document.getElementsByClassName("selectFlight")[0].style.display = "none";
           document.getElementsByClassName("flightDetails")[0].style.display = "block";
           document.getElementById("fromTo").innerHTML = orginVal + ' > ' + destinationVal;
           var departDay = moment(departureVal).format("Do MMMM YYYY");
           var arriveDay = moment(returnDateVal).format("Do MMMM YYYY");

           document.getElementById('oneWay').checked ?
               document.getElementById("FlightTime").innerHTML = 'Depart:' + departDay :
               document.getElementById("FlightTime").innerHTML = 'Depart:' + departDay + '<p>' + 'Arrive:' + arriveDay + '</p>';
           document.getElementById('roundTrip').checked ? document.getElementsByClassName("flightDetails")[0].style.marginTop = "60px" : '';

           var matches = flightDetails.filter(detail => detail.from === orginVal && detail.to === destinationVal);
           for (i = 0; matches[0].detail.length; i++) {
               var div = document.createElement('div');
               div.className = 'flightDetailBox';
               div.innerHTML = '<p id="flightCost">' + 'Rs' + matches[0].detail[i].price + '</p>' +
                   '<p id="flightID">' + matches[0].detail[i].FlightNum + '</p>' +
                   '<p id="fromTo">' + matches[0].from > +matches[0].to + '</p>' +
                   '<p id="departTime">' + matches[0].detail[i].departTime + '</p>' +
                   '<p id="ariveTime">' + matches[0].detail[i].arriveTime + '</p>' +
                   +'<button type="submit" id="bookTicketButton" onclick="bookTicket()">BOOK TICKET</button>';

               document.getElementById('flightDetails').appendChild(div);

           }
       }

   } catch (err) {
       ErrorMessage.innerHTML = err;
   }

}

function tripTypeFunc() {
   if (document.getElementById('oneWay').checked) {
       document.getElementById('returnDate').style.display = 'none';
   } else {
       document.getElementById('returnDate').style.display = 'block';
   }
}

function bookTicket() {
   document.getElementById('modal').style.display = "block";
}

$(function() {
   var headerSubText = $('#headerSubText').offset().left;
   $("#headerSubText").css({
       left: headerSubText
   }).animate({
       "left": "0px"
   }, "slow");

   var dateFormat = "mm/dd/yy",
       from = $("#departureDate")
       .datepicker({
           defaultDate: "+1w",
           changeMonth: true,
           numberOfMonths: 1
       })
       .on("change", function() {
           to.datepicker("option", "minDate", getDate(this));
       }),
       to = $("#returnDate").datepicker({
           defaultDate: "+1w",
           changeMonth: true,
           numberOfMonths: 2
       })
       .on("change", function() {
           from.datepicker("option", "maxDate", getDate(this));
       });

   function getDate(element) {
       var date;
       try {
           date = $.datepicker.parseDate(dateFormat, element.value);
       } catch (error) {
           date = null;
       }

       return date;
   }
});
header {
  font-size: 20px;
  background: #fff;
  color: green;
  padding: 20px 15px;
  text-align: center;
  font-weight: bold; }
  header p {
    margin: 0px;
    position: absolute;
    right: 0;
    font-size: 16px; }

form {
  margin-top: 15px;
  height: 100vw; }
  form .tripDetails {
    width: 25%;
    float: left;
    font-size: 18px; }
    form .tripDetails .flightInput {
      -webkit-border: 1px solid #ddd;
      -moz-border: 1px solid #ddd;
      -ms-border: 1px solid #ddd;
      border: 1px solid #ddd;
      display: block;
      height: 25px;
      -webkit-border-radius: 5px;
      -moz-border-radius: 5px;
      -ms-border-radius: 5px;
      border-radius: 5px;
      margin: 10px;
      width: 90%;
      padding: 5px 10px; }
    form .tripDetails .searchButton {
      border: none;
      background: #DD4E32;
      color: #fff;
      margin: auto;
      display: block;
      padding: 5px; }
  form .searchResults {
    width: 73%;
    float: right; }
    form .searchResults .selectFlight {
      -webkit-border: none;
      -moz-border: none;
      -ms-border: none;
      border: none;
      text-align: center;
      font-size: 35px; }
    form .searchResults .flightDetails {
      -webkit-border: 1px solid #ccc;
      -moz-border: 1px solid #ccc;
      -ms-border: 1px solid #ccc;
      border: 1px solid #ccc;
      height: 100px;
      margin: 30px 0px 15px 0px; }
    form .searchResults button {
      margin-right: 12px;
      background: #DD4E32;
      color: #fff;
      float: right;
      -webkit-border: none;
      -moz-border: none;
      -ms-border: none;
      border: none; }
    form .searchResults #modal {
      position: fixed;
      top: 0;
      left: 0;
      background: rgba(0, 0, 0, 0.8);
      z-index: 99999;
      height: 100%;
      width: 100%;
      display: none; }
      form .searchResults #modal #closeButton {
        text-align: center;
        padding: 5PX;
        margin-top: 15PX; }
      form .searchResults #modal .modalconent {
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%, -50%);
        background: #fff;
        width: 20%;
        padding: 50px;
        -webkit-border-radius: 10px;
        -moz-border-radius: 10px;
        -ms-border-radius: 10px;
        border-radius: 10px; }
    form .searchResults .searchResultsHeader {
      font-size: 20px; }
      form .searchResults .searchResultsHeader #fromTo {
        float: left; }
      form .searchResults .searchResultsHeader #FlightTime {
        float: right; }
        form .searchResults .searchResultsHeader #FlightTime p {
          margin: 0px; }
  form #errorMsg {
    color: red;
    padding-left: 15px; }

/* Iphone */
@media only screen and (min-device-width: 320px) and (max-device-width: 480px) and (-webkit-min-device-pixel-ratio: 2) {
  form {
    margin: 15px; }
    form .tripDetails {
      width: 100%;
      white-space: nowrap; }
    form .searchResults {
      width: 100%;
      margin-top: 30px; }
      form .searchResults .flightDetails {
        margin-top: 15px !important; }
      form .searchResults .searchResultsHeader #fromTo {
        width: 100%; }
      form .searchResults .searchResultsHeader #FlightTime {
        width: 100%;
        float: none; } }

/* tablets */
@media only screen and (min-device-width: 768px) and (max-device-width: 1024px) and (-webkit-min-device-pixel-ratio: 1) {
  form {
    margin: 15px; }
    form .tripDetails {
      width: 25%;
      white-space: nowrap; }
    form .searchResults {
      width: 70%;
      margin-left: 15px; }
      form .searchResults .searchResultsHeader #fromTo {
        width: 50%; }
      form .searchResults .searchResultsHeader #FlightTime {
        text-align: left; }
        form .searchResults .searchResultsHeader #FlightTime p {
          margin: 0px; } }
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Flight booking</title>
  <link rel="stylesheet" type="text/css" href="./css/main.css" />
  <link rel="stylesheet" href="https://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
  <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
  <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>
  <script src="./FlightBooking.js"></script>
</head>
<body>
  <header>
    T-Booking
    <p id="headerSubText">Book and enjoy your journey with us</p>
  </header>
  <form name="searchFlightForm" onsubmit="return searchFlights()">
    <div class="tripDetails">
      <input type="radio" name="tripType" id="oneWay" checked onclick="tripTypeFunc()">One way
      <input type="radio" name="tripType" id="roundTrip" onclick="tripTypeFunc()"> Round trip
      <input type="text" autocomplete="off" id="origin" list="originCountry" placeholder="Enter Origin" class="flightInput">
      <datalist id="originCountry"> </datalist>
      <input type="text"  autocomplete="off" id="desination" list="desinationCountry" placeholder="Enter Destination"
        class="flightInput" />
      <datalist id="desinationCountry"></datalist>
      <input type="text" id="departureDate" autocomplete="off" name="departureDate" placeholder="Departure Date" class="flightInput" />
      <input type="text" id="returnDate" autocomplete="off" name="returnDate" placeholder="Return Date" class="flightInput" />
      <input type="number" id="passengers" min="1" name="passengers" placeholder="Passengers" class="flightInput" />
      <p id="errorMsg"></p>
      <input type="button" value="Search" class="searchButton" onclick="searchFlights()">
    </div>
    <div class="searchResults">
        <p class="selectFlight">Please fill your flight details</p>
      <div class="searchResultsHeader">
        <div id="fromTo"></div>
        <div id="FlightTime"></div>
      </div>
     
      <div class="flightDetails" id="flightDetails">
        
        </div>
        <div>
          
          <div id="modal">
              <div class="modalconent">
                   <p>Ticket booked succesfully..!!</p>
                  <button id="closeButton">Close</button>
              </div>
          </div>
        </div>
      </div>

    </div>
  </form>


</body>

</html>

HTML

<div class="flightDetails" id="flightDetails"></div>

javascript

for (i = 0; matches[0].detail.length; i++) {
    var div = document.createElement('div');

    div.className = 'flightDetailBox';
    div.innerHTML = '<p id="flightCost">' + 'Rs' + matches[0].detail[i].price + '</p>'
    '<p id="flightID">' + matches[0].detail[i].FlightNum + '</p>'
    '<p id="fromTo">' + matches[0].from > +matches[0].to + '</p>'
    '<p id="departTime">' + matches[0].detail[i].departTime + '</p>'
    '<p id="ariveTime">' + matches[0].detail[i].arriveTime + '</p>' +
    '<button type="submit" id="bookTicketButton" onclick="bookTicket()">BOOK TICKET</button>';

    document.getElementById('flightDetails').appendChild(div);
}
答案

尝试下一个代码,你缺少<p>元素之间的字符串连接运算符,并且在所有这些中间有一个比较器符号<应该是一个字符串。

for (i = 0; matches[0].detail.length; i++)
{
    var div = document.createElement('div');
    div.className = 'flightDetailBox';        
    div.innerHTML = '<p id="flightCost">' + 'Rs' + matches[0].detail[i].price + '</p>' +
      '<p id="flightID">' +  matches[0].detail[i].FlightNum + '</p>' +
      '<p id="fromTo">' + matches[0].from + '>' + matches[0].to + '</p>' +
      '<p id="departTime">' + matches[0].detail[i].departTime + '</p>' +
      '<p id="ariveTime">' + matches[0].detail[i].arriveTime + '</p>' +
      '<button type="submit" id="bookTicketButton" onclick="bookTicket()">BOOK TICKET</button>';

   document.getElementById('flightDetails').appendChild(div);
}

另一种选择可能是使用template literals

for (i = 0; matches[0].detail.length; i++)
{
    var div = document.createElement('div');
    div.className = 'flightDetailBox';        
    div.innerHTML = `<p id="flightCost">Rs ${matches[0].detail[i].price}</p>` +
      `<p id="flightID">${matches[0].detail[i].FlightNum}</p>` +
      `<p id="fromTo">${matches[0].from} > ${matches[0].to}</p>` +
      `<p id="departTime">${matches[0].detail[i].departTime}</p>` +
      `<p id="ariveTime">${matches[0].detail[i].arriveTime}</p>` +
      `<button type="submit" id="bookTicketButton" onclick="bookTicket()">BOOK TICKET</button>`;

   document.getElementById('flightDetails').appendChild(div);
}
另一答案

我相信你可能会遗漏一些+标志,因此你的innerHTML文本没有正确连接。尝试将+运算符添加到您的代码中,如下所示:

for(i=0;matches[0].detail.length;i++){
  var div = document.createElement('div');
  div.className = 'flightDetailBox';        
  div.innerHTML ='<p id="flightCost">'+'Rs'+matches[0].detail[i].price+'</p>'      
        +'<p id="flightID">'+ matches[0].detail[i].FlightNum+'</p>'
        +'<p id="fromTo">'+matches[0].from > +matches[0].to+'</p>'
        +'<p id="departTime">'+matches[0].detail[i].departTime+'</p>'
        +'<p id="ariveTime">'+matches[0].detail[i].arriveTime+'</p>'+
        +'<button type="submit" id="bookTicketButton" onclick="bookTicket()">BOOK TICKET</button>';

        document.getElementById('flightDetails').appendChild(div);

}

以上是关于使用javascript添加基于json值的动态div标签的主要内容,如果未能解决你的问题,请参考以下文章

JavaScript:基于任意JSON动态生成树状图(动态生成vue-giant-tree所需idpid)

JavaScript:基于任意JSON动态生成树状图(动态生成vue-giant-tree所需idpid)

JavaScript:基于任意JSON动态生成树状图(动态生成vue-giant-tree所需idpid)

javascript里面的数组,json对象,动态添加,修改,删除示例

JSON 获取属性值的方法

JSON语法