HTML中的“未捕获的TypeError:bgColor不是函数”选择onchange

时间:2017-07-12 16:08:24

标签: javascript jquery html

我有一个带有onchange标记的HTML开关,该标记应该使用参数bgColor运行JavaScript函数this但是每当我尝试使用它时,它都会给我一个错误:Uncaught TypeError: bgColor is not a function。有什么想法吗?

HTML

<select id="selectBgColor" onchange="bgColor(this)">
    <option value="blue" selected>Blue</option>
    <option value="gray">Gray</option>
</select>

JavaScript

// The following is for changing graph color
var graphColor = "blue";
var graphBgColor = "rgba(106, 154, 177, 0.3)";
var graphBorderColor = "rgb(99, 121, 132)";
function bgColor(s) {
    graphColor = $(s).val();
    graphBgColor = graphColor == "blue" ? "rgba(106, 154, 177, 0.3)" : "rgba(0, 0, 255, 0.3)";
    graphBorderColor = graphColor == "blue" ? "rgb(99, 121, 132)" : "rgb(0, 0, 255)";
    update_temp_and_time();
}

任何帮助将不胜感激。谢谢!

1 个答案:

答案 0 :(得分:5)

为该功能使用其他名称。运行onxyz - 属性样式事件处理程序代码的环境有几个with子句(有效地)将元素(以及其他一些东西)的所有属性放在范围*中,优先于全局变量。在元素上有一个名为bgColor的旧的,不再标准的属性会阻碍您的全局功能。

另一个名称(如setBackgroundColor)将起作用:

&#13;
&#13;
// The following is for changing graph color
var graphColor = "blue";
var graphBgColor = "rgba(106, 154, 177, 0.3)";
var graphBorderColor = "rgb(99, 121, 132)";
function setBackgroundColor(s) {
    graphColor = $(s).val();
    graphBgColor = graphColor == "blue" ? "rgba(106, 154, 177, 0.3)" : "rgba(0, 0, 255, 0.3)";
    graphBorderColor = graphColor == "blue" ? "rgb(99, 121, 132)" : "rgb(0, 0, 255)";
    update_temp_and_time();
}
function update_temp_and_time() {
  console.log("graphColor = " + graphColor);
}
&#13;
<select id="selectBgColor" onchange="setBackgroundColor(this)">
    <option value="blue" selected>Blue</option>
    <option value="gray">Gray</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;

*这是许多原因之一,不使用onxyz - 属性样式事件处理程序,而不使用全局变量。相反,确保您的代码不在全局范围内(例如,将其包装在作用域函数中)并动态地连接处理程序。

E.g:

&#13;
&#13;
// Scoping function
(function() {
  // The following is for changing graph color
  var graphColor = "blue";
  var graphBgColor = "rgba(106, 154, 177, 0.3)";
  var graphBorderColor = "rgb(99, 121, 132)";

  $("#selectBgColor").on("change", function() {
      graphColor = $(this).val();
      graphBgColor = graphColor == "blue" ? "rgba(106, 154, 177, 0.3)" : "rgba(0, 0, 255, 0.3)";
      graphBorderColor = graphColor == "blue" ? "rgb(99, 121, 132)" : "rgb(0, 0, 255)";
      update_temp_and_time();
  });
  
  function update_temp_and_time() {
    console.log("graphColor = " + graphColor);
  }
})();
&#13;
<select id="selectBgColor"">
    <option value="blue" selected>Blue</option>
    <option value="gray">Gray</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;