[英]“Uncaught TypeError: bgColor is not a function” in HTML select onchange
我有一个带有onchange标签的HTML开关,该标签应使用参数this
来运行JavaScript函数bgColor
,但是每当我尝试使用它时,它都会给我一个错误: 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();
}
任何帮助,将不胜感激。 谢谢!
为函数使用其他名称。 运行onxyz
样式事件处理程序代码的环境有几个with
子句(有效地)将元素的所有属性(以及其他一些东西)放在scope *中,并且优先于全局变量。 元素上有一个旧的,不再标准的属性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); }
<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>
*这是不使用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); } })();
<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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.