模板文字在javascript中无法正常工作

时间:2018-03-21 08:56:34

标签: javascript

我使用.map方法返回对象的名称,并最终使用该名称填充表的innerHTML。

问题是我无法让它显示适当的值。

因此,例如,对于Almond_Divinity的风格,它将有一个包含三个表数据标记的Table行。第一个将有'Almond Divinity',第二个将有'.99'的价格,第三个将有链接。

我的javascript如下:

    var Menu = {
    Almond_Divinity : {name: 'Almond Divinity', price: .99, history: 'x', availability: 'x'},
    Mango_Sorbet : {name: 'Mango Sorbet', price: .99, history: '', availability: ''},
    Decaf : {name: 'Decaf', price: .99, history: '', availability: ''},
    Almond_Chocolate_Coconut : {name: 'Almond Chocolate Coconut', price: .99, history: '', availability: ''},
    Alpine_Fudge_Crunch : {name: 'Alpine Fudge Crunch', price: .99, history: '', availability: ''},
    Banana_Cream_Pie : {name: 'Banana Cream Pie', price: .99, history: '', availability: ''},
    Birthday_Cake : {name: 'Birthday Cake:', price: .99, history: '', availability: ''},
    Black_Raspberry_Chocolate_Crunch : {name: 'Black Raspberry Chocolate Crunch', price: .99, history: '', availability: ''},
    Blueberry_Cobbler : {name: 'Blueberry Cobbler', price: .99, history: '', availability: ''},
    Black_Walnut : {name: 'Black Walnut', price: .99, history: '', availability: ''},
    Mint_Chocolate_Chip : {name: 'Mint Chocolate Chip', price: .99, history: '', availability: ''},
    Caramel_Apple : {name: 'Caramel Apple:', price: .99, history: '', availability: ''},
    Almond_Divinity : {name: 'Almond Divinity', price: .99, history: '', availability: ''},
    Cherries_Jubilee : {name: 'Cherries Jubilee', price: .99, history: '', availability: ''},
    Tutti_Frutti : {name: 'Tutti Frutti', price: .99, history: '', availability: ''},
    Artic_Roll : {name: 'Artic Roll', price: .99, history: '', availability: ''},
    Dame_Blanche : {name: 'Dame Blanche', price: .99, history: '', availability: ''},
    Sizzling_Brownie : {name: 'Sizzling Brownie', price: .99, history: '', availability: ''},
    Choco_Taco : {name: 'Choco-Taco', price: .99, history: '', availability: ''}

};

window.onload = function () {
  // calls the keys property of the Object to find Menu and it's associated properties, and then uses the sort method to compare them and sort them alphabetically
  const sortedFlavors = Object.keys(Menu).sort(function(a, b) {return - (name[a] - name[b])});

  document.querySelector('#icecream_flavors').innerHTML = sortedFlavors.map(function icecream_flavor(currentValue, index, array) { return '<td>${currentValue}</td><td>$.99</td><td><a href="https://en.wikipedia.org/wiki/Ice_cream">History</a></td>'}).join('')
};

我的HTML是这样的:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Betty's icecream</title>
  <link rel="stylesheet" type="text/css" href="css/logo.css"/>
  <link rel="stylesheet" type="text/css" href="css/navbar.css"/>
  <link rel="stylesheet" type="text/css" href="css/body.css"/>
  <link rel="stylesheet" type="text/css" href="css/normalize.css"/>
  <link href="https://fonts.googleapis.com/css?family=Josefin+Slab" rel="stylesheet"/>
  <link href="https://fonts.googleapis.com/css?family=Quicksand" rel="stylesheet"/>
  <!-- <link rel="stylesheet" href="css/small.css" media="(max-width: 479px)" title="no title"> -->
  <style type="text/css" media="screen, print">
  @font-face {
    font-family: "KR Sweet Tooth";
    src: url("fonts/KR Sweet Tooth.ttf");
  }
  </style>
  <script
  src="https://code.jquery.com/jquery-3.3.1.js"
  integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
  crossorigin="anonymous"></script>
</head>
<body>
  <!-- <nav class="minus-padding">
    <div class="align-left">
      <ul>
        <li class="nav-li-left"><a href=""> Home </a></li>
        <li class="nav-li-left">Menu <a href=""></a></li>
        <li class="nav-li-left">Contact <a href=""></a></li>
      </ul>
    </div>
    <div class="align-right">
      <ul>
        <li class="nav-li-right">Parties</li>
        <li class="nav-li-right">Cakes</li>
      </ul>
    </div>
  </nav> -->
  <nav id="nav" class="minus-padding">
    <div class="align-left">
      <ul>
        <li class="nav-li-left"><a href="#"> Home </a></li>
        <li class="nav-li-left"><a href="#menu"> Menu </a></li>
        <li class="nav-li-left"><a href="#employees">Employees</a></li>
        <li class="nav-li-left"><a href="" onclick="newWindow()">View Mobile</a></li>
        <li class="nav-li-left"><a id="demo" href="#" >Contact</a></li>
      </ul>
    </div>
  </nav>
  <div>
    <img srcset="images/food-restaurant-fruits-orange.jpg  1280w"
    sizes="(min-width: 36em) 100vw,
    100vw"
    src="images/food-restaurant-fruits-orange.jpg"
    alt="A Banana Split" />
  </div>
    <div class="home">
      <h1>
        Betty's <br> <p id="logo"> s </p> Parlor
      </h1>
    </div>
  <div class="container">
    <div class="column-left">
      <div class="address">
        <p class="sidebar" id="sidebar-title">
          550 Ice Cream Lane
          Mulberry Hollow,
          Utah
          84501
          <br>
          <br>
          208-208-2080
        </p>
        <div class="address">
          <p class="sidebar">
            Put a bird on it 3 wolf moon street art synth, lumbersexual slow-carb poke live-edge brooklyn coloring book tattooed pour-over kombucha. Pitchfork sartorial marfa, tote bag pop-up hell of 90's lo-fi vape coloring book distillery fap fixie. Edison bulb chicharrones actually fanny pack, normcore salvia microdosing fixie activated charcoal direct trade food truck 3 wolf moon. Knausgaard chia copper mug cred, deep v roof party PBR&B kombucha semiotics pickled poutine man bun messenger bag. Shoreditch tbh intelligentsia hammock master cleanse banjo. Wayfarers pork belly skateboard freegan, leggings migas iPhone VHS photo booth knausgaard truffaut. Coloring book forage
          </p>
        </div>
      </div>
    </div>
    <div id="menu" class="column-right fl-scroll-link">
      <table class="table">
        <tr>
          <th id="header-modified">Flavor
          </th>
          <th>Price
          </th>
          <th>
            link
          </th>
        </tr>
        <tr id="icecream_flavors">

        </tr>
        <!-- <tr>
          <td>
            Almond Divinity
          </td>
          <td>
            $.99
          </td>
          <td>
            <a href="https://en.wikipedia.org/wiki/Ice_cream">History</a>
          </td>
        </tr>
        <tr>
          <td>
            Almond Chocolate Coconut
          </td>
          <td>
            $.99
          </td>
          <td>
            <a href="https://en.wikipedia.org/wiki/Ice_cream">History</a>
          </td>
        </tr>
        <tr>
          <td>
            Alpine Fudge Crunch
          </td>
          <td>
            $.99
          </td>
          <td>
            <a href="https://en.wikipedia.org/wiki/Ice_cream">History</a>
          </td>
        </tr>
        <tr>
          <td>
            Banana Cream Pie
          </td>
          <td>
            $.99
          </td>
          <td>
            <a href="https://en.wikipedia.org/wiki/Ice_cream">History</a>
          </td>
        </tr>
        <tr>
          <td>
            Birthday Cake
          </td>
          <td>
            $.99
          </td>
          <td>
            <a href="https://en.wikipedia.org/wiki/Ice_cream">History</a>
          </td>
        </tr>
        <tr>
          <td>Decaf
          </td>
          <td>$.99
          </td>
          <td>
            <a href="https://en.wikipedia.org/wiki/Ice_cream">History</a>
          </td>
        </tr>
        <tr>
          <td>
            Black Raspberry Chocolate Crunch
          </td>
          <td>
            $.99
          </td>
          <td>
            <a href="https://en.wikipedia.org/wiki/Ice_cream">History</a>
          </td>
        </tr>
        <tr>
          <td>
            Blueberry Cobbler
          </td>
          <td>
            $.99
          </td>
          <td>
            <a href="https://en.wikipedia.org/wiki/Ice_cream">History</a>
          </td>
        </tr>
        <tr>
          <td>
            Black Walnut
          </td>
          <td>
            $.99
          </td>
          <td>
            <a href="https://en.wikipedia.org/wiki/Ice_cream">History</a>
          </td>
        </tr>
        <tr>
          <td>
            Mint Chocolate Chip
          </td>
          <td>
            $.99
          </td>
          <td>
            <a href="https://en.wikipedia.org/wiki/Ice_cream">History</a>
          </td>
        </tr>
        <tr>
          <td>
            Caramel Apple
          </td>
          <td>
            $.99
          </td>
          <td>
            <a href="https://en.wikipedia.org/wiki/Ice_cream">History</a>
          </td>
        </tr>
        <tr>
          <td>
            Almond Divinity
          </td>
          <td>
            $.99
          </td>
          <td>
            <a href="https://en.wikipedia.org/wiki/Ice_cream">History</a>
          </td>
        </tr>
        <tr>
          <td>
            Almond Chocolate Coconut
          </td>
          <td>
            $.99
          </td>
          <td>
            <a href="https://en.wikipedia.org/wiki/Ice_cream">History</a>
          </td>
        </tr>
        <tr>
          <td>
            Alpine Fudge Crunch
          </td>
          <td>
            $.99
          </td>
          <td>
            <a href="https://en.wikipedia.org/wiki/Ice_cream">History</a>
          </td>
        </tr>
        <tr>
          <td>
            Banana Cream Pie
          </td>
          <td>
            $.99
          </td>
          <td>
            <a href="https://en.wikipedia.org/wiki/Ice_cream">History</a>
          </td>
        </tr>
        <tr>
          <td>
            Birthday Cake
          </td>
          <td>
            $.99
          </td>
          <td>
            <a href="https://en.wikipedia.org/wiki/Ice_cream">History</a>
          </td>
        </tr>
        <tr>
          <td>Decaf
          </td>
          <td>$.99
          </td>
          <td>
            <a href="https://en.wikipedia.org/wiki/Ice_cream">History</a>
          </td>
        </tr>
        <tr>
          <td>
            Black Raspberry Chocolate Crunch
          </td>
          <td>
            $.99
          </td>
          <td>
            <a href="https://en.wikipedia.org/wiki/Ice_cream">History</a>
          </td>
        </tr>
        <tr>
          <td>
            Blueberry Cobbler
          </td>
          <td>
            $.99
          </td>
          <td>
            <a href="https://en.wikipedia.org/wiki/Ice_cream">History</a>
          </td>
        </tr> -->
      </table>
    </div>
    <div class="empty">

      <div class="row">
        <h2 id="employees">Employees</h2>
      </div>
    </div>
    <div style="width: 100%; height: 10px">

    </div>

    <div class="row-full">
      <div class="center">
        <!-- grids  -->
        <div class="grid">
          <img class="circle" src="images/bow-tie-businessman-fashion-man.jpg" alt="boss image" />
          <a href="#"><p>Meet Ben: An impulsive Vanilla lover.</p></a>
        </div>
        <div class="grid">
          <img class="circle" src="images/man-couple-people-woman.jpg" alt="coworkers boxing" />
          <a href="#"><p>Meet Dolley Madison: An argumentative mint chocolate-chipper. </p></a>
        </div>
        <div class="grid">
          <img class="circle" src="images/pexels-photo (1).jpg" alt="man lifting weights" />
          <a href="#"><p>Meet Jerry: A strawberry introvert. </p></a>
        </div>
        <div class="grid">
          <img class="circle" src="images/pexels-photo-89524 (1).jpg" alt="little girl" />
          <a href="#"><p>Meet Robert Green: A flirtatious chocolate lover. </p></a>
        </div>
        <div class="grid">
          <img class="circle" src="images/pexels-photo-127968.jpg" alt="little girl floating" />
          <a href="#"><p>Meet Nicholas Lemery: A sherbet pessimist. </p></a>
        </div>
        <div class="grid">
          <img class="circle" src="images/pexels-photo.jpg" alt="little girl surprised"/>
          <a href="#"><p>Meet H. Glasse: An aggressive Rocky Roader. </p></a>
        </div>


        <footer class="footer">
          <div class="footer-row">
            <ul id="footer-ul">
              <li class="footer-li"><a href="">Franchise</a></li>
              <li class="footer-li"><a href="">Jobs</a></li>
              <li class="footer-li"><a href="">Inquiries</a></li>
              <li class="footer-li"><a href="">Parties</a></li>
              <li class="footer-li"><a href="">Adventure</a></li>
              <li class="footer-li"><a href="">Coupons</a></li>
            </ul>
          </div>
          <div class="">
            <p class="footer-p">
              copyright © Trrapp
            </p>
          </div>
        </footer>

      </div>
    </div>


  </div>
  </body>
  <script src="src/menu.js"
  <script>
  // Select all links with hashes
  $('a[href*="#"]')
    // Remove links that don't actually link to anything
    .not('[href="#"]')
    .not('[href="#0"]')
    .click(function(event) {
      // On-page links
      if (
        location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '')
        &&
        location.hostname == this.hostname
      ) {
        // Figure out element to scroll to
        var target = $(this.hash);
        target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
        // Does a scroll target exist?
        if (target.length) {
          // Only prevent default if animation is actually gonna happen
          event.preventDefault();
          $('html, body').animate({
            scrollTop: target.offset().top
          }, 1000, function() {
            // Callback after animation
            // Must change focus!
            var $target = $(target);
            $target.focus();
            if ($target.is(":focus")) { // Checking if the target was focused
              return false;
            } else {
              $target.attr('tabindex','-1'); // Adding tabindex for elements not focusable
              $target.focus(); // Set focus again
            };
          });
        }
      }
    });
  </script>
  <script>
    function newWindow() {
      newwindow = window.open('https://trrapp12.github.io/ice-cream/', '', 'width=680,height=680')

      function resizeWinTo() {
        newwindow.resizeTo(20, 20);
        newwindow.focus();
        alert("inner function called")
      };
      resizeWinTo();
    };

  </script>
</html>

我得到的结果是:

link to image

您可以提供任何帮助,我们将不胜感激。由于我在这里没有声称自己的优点,因此不需要适用评论。

3 个答案:

答案 0 :(得分:1)

您需要将字符串括在反引号中以获取字符串插值:

sortedFlavors.map(function(currentValue) {
  return `<td>${currentValue}</td><td>$.99</td><td><a href="https://en.wikipedia.org/wiki/Ice_cream">History</a></td>`
}).join('')

另外,肯定的是,这些项目不会被排序为字符串的减法操作,导致NaN

答案 1 :(得分:1)

您需要使用template literal而不是单引号'

//notice that ' is replaced with `

  document.querySelector('#icecream_flavors').innerHTML =   
        sortedFlavors.map( function icecream_flavor(currentValue, index, array) { 
            return `<td>${currentValue}</td><td>$.99</td><td><a href="https://en.wikipedia.org/wiki/Ice_cream">History</a></td>`
   }).join('');

答案 2 :(得分:-1)

<table id="icecream_flavors"></table>    
 $(document).ready(function(){

            var temp="";
            for(var prop in Menu){
            temp+="<tr><td>"+Menu[prop].name+"</td><td>"+Menu[prop].price+"</td><td>"+Menu[prop].availability+"</td></tr>";
            }
            $("#icecream_flavors").append(temp);


            });