函数未定义..我的函数调用不起作用

Function not defined....My Function Call is not Working

本文关键字:不起作用 函数调用 我的 未定义 函数      更新时间:2023-09-26

我需要这段代码的帮助。我不断得到错误changeBG没有定义。

代码的工作方式是,当我选择一个单选按钮时,背景会发生变化。如果我在onclick事件中将函数更改为内联函数,则它可以工作,但如果我将函数移到脚本部分,则它不工作,例如:<input type="radio" id="red" name="change1" value=1 onclick="document.body.style.backgroundColor='red'" /><label for="red">Red</label><br />正在更改背景红色

但是当我在脚本部分创建一个函数并在onlick事件中调用该函数时,它不起作用,

不起作用的代码示例:

脚本:

<script type="text/javascript">      
  function changeBG(n)       
  {
    if (n==1)
        document.body.style.backgroundColor='red'";
    if (n==2)
        document.body.style.backgroundColor='yellow'";
    if (n==3)
        document.body.style.backgroundColor='green'";
    if (n==4)
        document.body.style.backgroundColor='orange'";      
  }
  </script>

HTML:

     <form id="jp2" name="jp2" method="get">                                                                          
        <input type="radio" id="red" name="change1" value=1 onclick="changeBG(1)" />
        <label for="red">Red</label><br />
        <input type="radio" id="Yellow" name="change1" value=2 onclick="changeBG(2)" />
        <label for="yellow">Yellow</label><br />
        <input type="radio" id="Green" name="change1" value=3 onclick="changeBG(3)"  />
        <label for="green">Green</label><br />
        <input type="radio" id="Orange" name="change1" value=4  onclick="changeBG(4)" />
        <label for="orange">Orange</label><br />
     </form>
backgroundColor='red'"
backgroundColor='yellow'"
backgroundColor='green'"
backgroundColor='orange'"

你看到那些额外的"引号了吗?把他们赶走。

您的工作代码

在Firefox中,这会导致以下控制台错误。您应该学习如何进行一些简单的调试,以便尽早发现这些错误。

SyntaxError:未终止的字符串文字

使用正确的引号。你用错了额外的引号。如CCD_ 3。由于这些额外的引用导致JS错误,您就是错误,即未定义函数。

将js更改为following。

 function changeBG(n) {
   if (n == 1)
     document.body.style.backgroundColor = 'red';
   if (n == 2)
     document.body.style.backgroundColor = 'yellow';
   if (n == 3)
     document.body.style.backgroundColor = 'green';
   if (n == 4)
     document.body.style.backgroundColor = 'orange';
 }
<form id="jp2" name="jp2" method="get">
  <input type="radio" id="red" name="change1" value=1 onclick="changeBG(1)" />
  <label for="red">Red</label>
  <br />
  <input type="radio" id="Yellow" name="change1" value=2 onclick="changeBG(2)" />
  <label for="yellow">Yellow</label>
  <br />
  <input type="radio" id="Green" name="change1" value=3 onclick="changeBG(3)" />
  <label for="green">Green</label>
  <br />
  <input type="radio" id="Orange" name="change1" value=4 onclick="changeBG(4)" />
  <label for="orange">Orange</label>
  <br />
</form>