我正在编写一个小测验应用程序,正在查看设置div或文本字段值的不同方法
作为学习过程,我尝试使用多种不同的方法设置页面元素的值
document.getElementById(" showQuestion2")。innerHTML = VAULE //这可以使用getElementById方法。
document.showQuestion3.value = allQuestions [2] .question +" \ n" + allQuestions [2] 这不起作用。返回 - TypeError:document.showQuestion3未定义。是我的错: 一个。误解语法document.element_name.value只是简单的错误
我想确认的是:
使用表单时,您可以通过name属性导航DOM / BOM以设置/检索值
尝试更改/设置元素的HTML时,不能使用命名法: document.ID.innerHTML - 您需要使用getElementbyID方法,否则无法执行此操作
样本/实验代码
<script type="text/javascript">
function btnShowQuestion_onclick(){
var allQuestions = [
{question: "Who is Prime Minister of the United Kingdom?",
choices: ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"],
correctAnswer:0},
{question: "What is Superman's real name?",
choices: ["Carmen Electra", "Gordon Brown", "Clark Kent", "Tony Blair"],
correctAnswer:2},
{question: "What if god was one of us?",
choices: ["would he be a stranger on the bus", "Would he be a cat ", "she would do a duet with britney spears", "it would smite you dead"],
correctAnswer:2}
];
document.form1.questionDisplay.value = allQuestions[0].question+"\n"+allQuestions[0].choices+"\n";
document.getElementById("showQuestion2").innerHTML = allQuestions[1].question+"\n"+allQuestions[1].choices+"\n";
document.showQuestion3.value= allQuestions[2].question+"\n"+allQuestions[2].choices+"\n";
};
</script>
</head>
<body>
<div class="row">
<div class="col-md-12">
<h1>Let' play a game</h1>
<div id="showQuestion2"></div>
<div name="showQuestion3"></div>
<form name="form1" action="">
<textarea rows="10" cols="35" name="questionDisplay"></textarea>
<br />
<input type="button" value="show question" name="btnShowVisited" onclick="btnShowQuestion_onclick()" />
</form>
</div>
</div>
答案 0 :(得分:0)
我建议你也看一下jsrender jquery库,你可以用简单的符号动态生成用户界面并使用ajax调用。 请查看此[https://github.com/BorisMoore/jsrender]以获取更多参考资料
<script id="movieTemplate" type="text/x-jsrender">
<div>
{{:#index+1}}: <b>{{>name}}</b> ({{>releaseYear}})
</div>
</script>
<div id="movieList"></div>
<script type="text/javascript">
var movies = [
{ name: "The Red Violin", releaseYear: "1998" },
{ name: "Eyes Wide Shut", releaseYear: "1999" },
{ name: "The Inheritance", releaseYear: "1976" }
];
// Render the template with the movies data and insert
// the rendered HTML under the "movieList" element
$( "#movieList" ).html(
$( "#movieTemplate" ).render( movies )
);
</script>
在上面的代码电影中,数据使用脚本标签
在movieList div中呈现