如何在脚本标签中编写HTML代码?

时间:2019-09-03 23:52:54

标签: javascript html

我正在努力将我的html代码的某些部分写入脚本标记中间的文件中。

我有document.Write当前,但它没有通过我的验证器,需要一个解决方案。香港专业教育学院试图创建一个文本节点和追加,以及innerHTML,但似乎都行不通,有什么帮助吗?

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

<!-- 
   New Perspectives on JavaScript, 2nd Edition
   Tutorial 3
   Case Problem 2

   Congressional Election Results
   Author: 
   Date:   

   Filename:         election.htm
   Supporting files: back.jpg, logo.jpg, results.css, votes.js

-->
   <head>
   <title>Congressional Races</title>
   <link href="results.css" rel="stylesheet" type="text/css" />
   <script src="votes.js" type="text/javascript"></script>
   <script src="barchart.js" type="text/javascript"></script>

   <script>
      function totalVotes(votes) {
         var total=0;
         for (var i=0; i<votes.length; i++) total+=votes[i];
         return total;
      }
      function calcPercent(item, sum) {
         return Math.round(100*item/sum);
      }

      function createBar(partyType, percent) {
         switch (partyType) {
            case "D": barText="<td class='dem'> </td>";break;
            case "R": barText="<td class='rep'> </td>";break;
            case "I": barText="<td class='ind'> </td>";break;
            case "G": barText="<td class='green'> </td>";break;
            case "L": barText="<td class='lib'> </td>";break;
         }

         for (var j=1; j <= percent; j++) document.write(barText);
      }

      function showResults(race, name, party, votes) {

         var totalV=totalVotes(votes);

         document.write("<h2>"+race+"</h2>");
         document.write("<table>");
         document.write("<tr><th>Candidate</th><th class='num'>Votes</th><th class='num'>%</th></tr>");

         for (var i=0; i < name.length; i++) {
            document.write("<tr>");
            document.write("<td>"+name[i]+" ("+party[i]+")</td>");
            document.write("<td class='num'>"+votes[i]+"</td>");

            var percent = calcPercent(votes[i],totalV);
            document.write("<td class='num'>("+percent+"%)</td>");
            createBar(party[i], percent);
            document.write("</tr>");
         }

         document.write("</table>");
      }
   </script>
</head>

<body>

   <div id="intro">
      <p><img src="logo.jpg" alt="Election Day Results" /></p>
      <a href="#">Election Home Page</a>
      <a href="#">President</a>
      <a href="#">Senate Races</a>
      <a href="#">Congressional Races</a>
      <a href="#">State Senate</a>
      <a href="#">State House</a>
      <a href="#">Local Races</a>
      <a href="#">Judicial</a>
      <a href="#">Referendums</a>
   </div>

   <div id="results">
      <h1>Congressional Races</h1>
      <script type="text/javascript">
            showResults(race[0],name1,party1,votes1);
            showResults(race[1],name2,party2,votes2);
            showResults(race[2],name3,party3,votes3);
            showResults(race[3],name4,party4,votes4);
            showResults(race[4],name5,party5,votes5);
         </script>

   </div>

</body>
</html>

3 个答案:

答案 0 :(得分:2)

我建议您不要使用 document.write ,因为随后的每个document.write都会覆盖前一个。相反,我建议您深入研究模板文字:https://www.youtube.com/watch?v=NgF9-pdTDGs document.body.innerHTML

const variableExample = 'Heading content';
document.body.innerHTML = `
<div>
  <h1>${variableExample}</h1>
  <p>I am some content!!</p>
</div>
`;

答案 1 :(得分:1)

您已经告诉解析器“这是一个XML文档,特别是遵循XHTML规则的XML文档;请照这样处理”,方法是在文档顶部添加样板:

<?xml version="1.0" encoding="UTF-8" ?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

但是随后您切换到了另一种完全不是合法XML的语言:

<script>
  function totalVotes(votes) {
    var total=0;
    for (var i=0; i<votes.length; i++) total+=votes[i];

XML解析器会嗡嗡作响(注意到您在type标记中缺少必需的<script>属性),直到看到i<votes.length;。它认为<votes.length是标记的开头,非常混乱,并开始向左右抛出错误。要告诉解析器“只是忽略这一部分;它不适合您”,请添加CDATA tags(并在页面作为HTML而不是XHTML用作页面时将它们注释掉):

<script type="text/javascript">
  /*<![CDATA[*/
  function totalVotes(votes) {
    var total=0;
    for (var i=0; i<votes.length; i++) total+=votes[i];
    return total;
  }
  /*]]>*/
</script>

(这将验证但不起作用,因为document.write doesn't work in XML for compliance reasons。没关系,因为您really shouldn't be using document.write to begin with。只需使用innerHTML解决方案。)


更好的方法

处理XML和XHTML令人头疼,除非您特别需要(不需要这样做),否则最好使用modern HTML5。样板变得更短:

<!doctype html>

<html>

就是这样。没有DTD,没有名称空间,没有CDATA。就是这样。

答案 2 :(得分:0)

除非您要编写完整的javascript Web组件,否则请保持HTML为HTML。当您要更改布局时,如果未将其隐藏在javascript中,则可以更轻松地在HTML编辑器中处理HTML。

我将使用<template> element。请注意,如果您需要支持IE,则需要使用pollyfill<script type="text/template>,这需要一些额外的工作。

function showResults(race, name, party, votes) {
  //Clone the template
  var clone = document.importNode(document.getElementById("templateRace").content, true);
  //To update the clone we need to move it to a temporary item
  var holder = document.createElement('div');
  holder.appendChild(clone);
  //replace the simple data
  holder.innerHTML = holder.innerHTML
    .replace(/{{race}}/g, race);  
  var totalVotes = votes.reduce(function(acc, curr) {
    return acc + curr
  });
  
  //Add Rows
  for (var i = 0; i < name.length; i++) {
    //Clone the row template
    var rowClone = document.importNode(document.getElementById("templateRow").content, true);
    var percent = 100 * votes[i]/totalVotes;
    var partyClasses = {
      "D": "dem",
      "R": "rep",
      "I": "ind",
      "G": "green",
      "L": "lib"
    }
    //To update the clone we need to move it to a temporary item
    var rowHolder = document.createElement('tbody');
    
    rowHolder.appendChild(rowClone);
    //replace the simple data
    rowHolder.innerHTML = rowHolder.innerHTML
      .replace(/{{name}}/g, name[i])
      .replace(/{{party}}/g, party[i])
      .replace(/{{votes}}/g, votes[i])
      .replace(/{{percent}}/g, percent)
      .replace(/{{percWidth}}/g, parseInt(percent * 2, 10))
      .replace(/{{partyClass}}/g, partyClasses[party[i]]);
      
      //Add the row to the tbody
      holder.querySelector("tbody").appendChild(rowHolder.querySelector("tr"));
  }

  //Add the full details
  document.getElementById("res").appendChild(holder.querySelector("section"));
  
}


showResults("Race 1", ["Bill", "Ben", "Brian", "Betty"], ["D", "R", "I", "G"], [15, 25, 10, 50]);
//showResults(race[0],name1,party1,votes1);
/*showResults(race[1],name2,party2,votes2);
showResults(race[2],name3,party3,votes3);
showResults(race[3],name4,party4,votes4);
showResults(race[4],name5,party5,votes5);*/
.dem {background-color: red;}
.rep {background-color: blue;}
.ind {background-color: yellow;}
.green {background-color: green;}
.lib {background-color: black;}
.party {display:inline-block;}
<body>

  <div id="intro">
    <p><img src="logo.jpg" alt="Election Day Results" /></p>
    <a href="#">Election Home Page</a>
    <a href="#">President</a>
    <a href="#">Senate Races</a>
    <a href="#">Congressional Races</a>
    <a href="#">State Senate</a>
    <a href="#">State House</a>
    <a href="#">Local Races</a>
    <a href="#">Judicial</a>
    <a href="#">Referendums</a>
  </div>

  <div id="results">
    <h1>Congressional Races</h1>
    <div id="res">
    </div>

    <template id="templateRace">
        <section>
        <h2>{{race}}</h2>
        <table>
          <thead>
            <tr>
            <th>Candidate</th><th class='num'>Votes</th><th class='num'>%</th>
            </tr>
          </thead>
          <tbody>            
          </tbody>
        </table>
        </section>
      </template>
    <template id="templateRow">      
        <tr>
          <td>{{name}} ({{party}})</td>
          <td class="num">{{votes}}</td>
          <td class="num">{{percent}}</td>
          <td class="party {{partyClass}}"><div style="width:{{percWidth}}px; height:100%"> </div> </td>
        </tr>
      </template>


  </div>