HTML select onchange中的"未捕获的TypeError:bgColor不是函数"

The*_*Guy 0 html javascript jquery

我有一个带有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>
Run Code Online (Sandbox Code Playgroud)

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();
}
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激.谢谢!

T.J*_*der 5

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

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

// 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);
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)


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

例如:

// 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);
  }
})();
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)