"Function is undefined" 处理 Javascript 中定义的函数时出错

"Function is undefined" error when dealing with defined functions in Javascript

我在 JavaScript 休息后尝试使用函数(因为它的语法让我很伤心)并且它再次决定再次残忍地对待我,忽略我的函数。

<script type="text/javascript">
channel = 1
channel_array = ["welcome_mat.html", "http://www.youtube.com/user/1americanews"];
function Oooh(e){
 var unicode=e.keyCode? e.keyCode : e.charCode
 alert(unicode);
 if (unicode == 38);{
  alert("You hit the up button.");
  if (channel == 65);{
   channel = 1;
   document.getElementById("Frame").src = channel_array[channel]
  }
  else{
   channel = channel + 1;
   document.getElementById("Frame").src = channel_array[channel]
  }
 }
}
</script>
<input id="text2" type="text" size="2" maxlength="1" onkeyup="Oooh(event); this.select()" />
<script type="text/javascript">
document.getElementById("Frame").src="http://www.youtube.com/user/1americanews";
document.getElementById("text2").focus();
</script>

第一个 if 语句后有一个分号

替换

if (channel == 65);{

if (channel == 65){

您提到您在使用 JavaScript 的语法时遇到了问题,而您的代码确实如此。

更正后的版本是:

<script type="text/javascript">
    var channel = 1;
    var channel_array = ["welcome_mat.html", "http://www.youtube.com/user/1americanews"];
    function Oooh(e) {
        var unicode=e.keyCode ? e.keyCode : e.charCode;
        alert(unicode);
        if (unicode == 38) {
            alert("You hit the up button.");
            if (channel == 65) {
                channel = 1;
                document.getElementById("Frame").src = channel_array[channel];
            }
            else {
                channel = channel + 1;
                document.getElementById("Frame").src = channel_array[channel];
            }
        }
    }
</script>
<input id="text2" type="text" size="2" maxlength="1" onkeyup="Oooh(event); this.select()">
<script type="text/javascript">
    document.getElementById("Frame").src = "http://www.youtube.com/user/1americanews";
    document.getElementById("text2").focus();
</script>

您的脚本中存在一些错误,原因是缺少 and/or 无效 tokens/semicolons。

它应该是这样的:

function Oooh(e) {
    var unicode = e.keyCode ? e.keyCode : e.charCode;
    alert(unicode);
    if (unicode === 38) {
        alert("You hit the up button.");
        if (channel === 65) {
            channel = 1;
            document.getElementById("Frame").src = channel_array[channel];
        } else {
            channel = channel + 1;
            document.getElementById("Frame").src = channel_array[channel];
        }
    }
}

主要问题是;在你的 if 语句之后。

另请注意: 在适当行的末尾使用分号是 JS 中良好的编码风格。 使用 === 而不是 == 以确保类型安全的比较。 尝试将您的 JS 代码放在外部文件中。