你快到了,实际上javascript不会直接“回显”值,它会使用调试控制台记录值,如果我的记忆没有失败console.log(your value);
,类似于AS2 。trace()
要将信息“输出”到文档,您应该查看document.write
当您使用 document.write 时,它将直接写入文档末尾。
“正确”的方法是创建一个 DOM 元素,其中包含您想要的元素,然后将其附加到所需的元素。看看评论
<!-- Be Aware to use the onchange trigger on select boxes, if you use onclick the function will run, even
if you didn't really chose any option -->
<select id="test1" onchange="checkField()">
<!-- Is good to have a first non-value option, better to trigger the onchange event, if you have
Select A Group as first option and you click on it, it didn't really "Change", you would have to
pick B Group and then A Group again to trigger the onchange event correctly. -->
<option value="">-- select an option --</option>
<!-- You can have a value attribute on the options, so it's easy to process when programming
while displaying a more detailed description to the users -->
<option value="A">Selected A Group</option>
<option value="B">Selected B Group</option>
</select>
<!-- We create an empty element where we are gonna place the new Select -->
<div id="newSelect"></div>
<!-- By Placing the Javascript on the end of <body>, we ensure that all the DOM elements loaded before running the script -->
<script>
function checkField(){
var newSelect = document.getElementById('newSelect'); //targeting container;
var temp = document.getElementById('test1').value;
//Some tasks we do always the option chose is not the first custom one, so we don't have to repeat it
//on the two If's below
if(temp !== ""){
// We remove the select if we placed one already before, so we can add the new one,
// For example if we chose B Group but changed our mind and Chose A Group later.
if(oldChild = newSelect.getElementsByTagName('select')[0]){
oldChild.remove();
}
var select = document.createElement("select");
select.setAttribute('id', 'newSelect');
}
if(temp === "A"){
//you could do JUST:
//body.innerHTML = "all the html you want in here" instead of all the code following;
//but all those code is supposed to be the "correct way" of adding elements to the HTML,
//Google a bit about that for detailed explanations
var option1 = document.createElement("option");
option1.value = 1;
option1.text = "Option 1";
var option2 = document.createElement("option");
option1.value = 2;
option2.text = "Option 2";
select.appendChild(option1);
select.appendChild(option2);
newSelect.appendChild(select);
} else {
var option1 = document.createElement("option");
option1.value = 3;
option1.text = "Option 3";
var option2 = document.createElement("option");
option1.value = 4;
option2.text = "Option 4";
select.appendChild(option1);
select.appendChild(option2);
newSelect.appendChild(select);
}
}
</script>
当然,如果您要输出的数据具有模式,则可以使用循环来缩短它的时间,但是让我们以“简单”的方式来做,这样您就可以掌握 Javascript。
希望这一切对你有帮助!!