从外部javascript文件添加html

时间:2017-02-25 09:54:16

标签: javascript jquery html css

我是javascript的新手,所以请不要刻录。

我有一个文件Index.html,我无法改变,甚至有点。

Index.html调用javascript文件experiment.js。我想要做的是添加我的HTML代码并使用experiment.js中的javascript调用css文件style.css。

这是我在experiment.js写的代码

    var link = document.createElement('link');
link.setAttribute('rel', 'stylesheet');
link.setAttribute('type', 'text/css');
link.setAttribute('href', 'style.css');
document.getElementsByTagName('head')[0].appendChild(link);

var htmlcode;
htmlcode="";
htmlcode="<div class="transbox1"> </div> <p id="heading">OHMs LAW EXPERIMENT</p>";
htmlcode=htmlcode+"<div class="transbox2"></div>";
htmlcode=htmlcode+"<p id="ohmlaw">Ohms Law states that Voltage across any resistan;e is Proportional to Current Flowing through the circuit.<br>V=IR (V=Voltage(Volt) I=Current(Ampere) R=Resistance(Ohm))</p>";
htmlcode=htmlcode+"<div id="abbr"><img src="abbr.jpg" height="200" width="150"/> </div>";
htmlcode=htmlcode+"<div id="img1" ><img id="loadingImage" src="graph.jpg" style="visibility:hidden"height="280" width="380"/></div>";
htmlcode=htmlcode+"<div id="circuit" ><img src="circuit.png" height="660" width="1130"/></div>";
htmlcode=htmlcode+"<div id="battery" ><img id="cells" src="reverse.png" style="visibility:hidden" height="180" width="270"/></div>";
htmlcode=htmlcode+"<table id="myTable">";
htmlcode=htmlcode+"<tr>";
htmlcode=htmlcode+"<th>Voltage</th>";
htmlcode=htmlcode+"<th>Current</th>";
htmlcode=htmlcode+"<th>Voltage/Current</th>";
htmlcode=htmlcode+"</tr>";
htmlcode=htmlcode+"</table>";
htmlcode=htmlcode+"<button  id="startQuiz" class="button" onclick="startQuiz()">Start Quiz</button>";
htmlcode=htmlcode+"<button  id="next" class="button" onclick="nextQuiz()">Next</button>";
htmlcode=htmlcode+"<button  id="submit" class="button" onclick="checkQuiz()">Submit answer</button>";
htmlcode=htmlcode+"<button  id="showQuiz" class="button" onclick="showQuiz()" >Show Answers</button>";
htmlcode=htmlcode+"<button  id="graph" class="button" onclick="showGraph()">Graph</button>";
htmlcode=htmlcode+"<button  id="note" class="button" onclick="note()">Note Values</button>";
htmlcode=htmlcode+"<button  id="reverse" onclick="reverseP()">Reverse Polarity</button>";
htmlcode=htmlcode+"<input type="checkbox" id="reverseCheck">"    
document.write(htmlcode);

这似乎无效。 请帮忙。

1 个答案:

答案 0 :(得分:0)

您遇到问题,因为您没有转义双引号:

htmlcode = "<div class=\"transbox1\"> </div> <p id=\"heading\">OHMs LAW EXPERIMENT</p>";

您应该考虑对字符串使用简单的引号,这样您就不必转义双引号:

htmlcode = '<div class="transbox1"></div><p id="heading">OHMs LAW EXPERIMENT</p>';

其他建议,你应该使用“+ =”符号

htmlcode = '<div class="transbox1"></div>';
htmlcode += '<div class="transbox2"></div>';