我正在使用的Javascript程序的帮助

问题描述

|| 我正在完成一项任务,遇到了一个对我来说很奇怪的问题,我不知道如何解决。 很难解释,但希望我能对某些人理解得足够好。 我正在使用HTML表单(单选按钮,复选框,选择框,文本框),我的老师给了我们有关JavaScript中HTML的任务。 我已经完成了所有任务,但是经过一定时间后,当我尝试声明一个对象并从表单中提取一些HTML时,它说它是“ null”。但是,如果我将其放在页面顶部,它将可以使用,但随后它会取消其中的任何内容。 (我知道这听起来很混乱,但是也许看到一些代码可能会有所帮助。)
   <html>
<body>
<script language=\"javascript\">
<!--
function fred ()
{


option1=document.f1.zooanimal.option1

if(document.f1.game1.checked||document.f1.game2.checked||document.f1.game3.checked||document.f1.game4.checked)
{
return true
}
else
{
alert(\"Must Select at least ONE CheckBox Value!!!\")
}


if (document.f1.zooanimal.selectedindex=option1);
{
alert(\"Must Select Option other than default value!\");
}



bigtextstr=document.f1.bigtext.value
bigedit=bigtextstr.replace(/ /g,\"+\")
bigedit2=bigedit.replace(/[\\r\\n]/g,\"\")

document.write(\"Characters in Text Area Before Edits=\"+\"<br>\")
biglen=bigtextstr.length
document.write(biglen+\"<br>\")

document.write(\"Characters in Text Area After Edits=\"+\"<br>\")
newbiglen=bigedit2.length
document.write(newbiglen+\"<br>\")    
}


-->
</script>
<p>
<form name=\"f1\">
<br>
Name <input type=\"text\" name=\"nametext\" size=\"30\" value=\"First Last\"><p>
List your favorite things to do <P><textarea name=\"bigtext\" rows=\"5\" cols=\"40\">default value</textarea>

<p>What is your favorite animal to see at the zoo?

<select name=\"zooanimal\">
  <option name= \"option1\" selected=\"yes\">default value
  <option name=\"option2\">elephants
  <option name=\"option3\">giraffes
  <option name=\"option4\">tigers
  <option name=\"option5\">seals
</select>

<p>
What is your favorite color?<br><p>
   blue <input name=\"rb\" type=\"radio\" value=\"blue\" checked> green <input name=\"rb\" type=\"radio\" value=\"green\">
  pink <input name=\"rb\" type=\"radio\" value=\"pink\"> yellow <input name=\"rb\" type=\"radio\" value=\"yellow\"> red <input name=\"rb\" type=\"radio\" value=\"red\"> black <input name=\"rb\" type=\"radio\" value=\"black\"></p>

Which of these games do you play?<br><p>
  Starcraft <input name=\"game1\" value=\"Starcraft\" type=\"checkBox\"> World of Warcraft <input name=\"game2\" value=\"WorldofWarcraft\" type=\"checkBox\"> 
 League of Legends <input name=\"game3\" value=\"LeagueofLegends\" type=\"checkBox\"> none <input name=\"game4\" value=\"none\"
 type=\"checkBox\"><P>



<p><input type=\"button\" value=\"EDIT AND REPORT\" onClick=\"fred()\">


<p>

<p>
</form>
</body>
</html>
现在看一下脚本部分,到那时为止一切正常,但是如果我尝试在此之后添加其他任何形式的引用,它将表示为null。我很困惑,已经为此工作了好几个小时。有人可以帮忙吗?     

解决方法

当引用[单个]对象时,应该使用
getElementById(\'elementid\')
getElementsByName(\'elementname\')[0]
来获取它们,而不是尝试通过父\'nodes \'遍历到所需的元素。 还将JavaScript放在文档的开头或正文的底部。这些是不应在onload上运行的脚本的最佳位置;) 此外,请注意\'document.write \'将覆盖整个文档。您应该在页面中放置一个ѭ3,,并为其指定一个唯一的ID ...
<p id=\"unique_id_alerts\"></p>
并这样写:
document.getElementById(\'unique_id_alerts\').innerHTML = \'Output goes here.\';
    ,或者如果您想从HTML元素获取数据 您可以使用
jQuery(\"#ElementId\").text();