JavaScript错误:未捕获的TypeError:foo不是函数 [英] JavaScript Error: Uncaught TypeError: foo is not a function
问题描述
由于某些原因,JavaScript似乎无法识别我的功能。
For some reason JavaScript doesn't seem to recognise my function.
我在某个HTML中有一个按钮:
I have a button in some HTML:
<button type="button" class="btn btn-default" id="lightOn" onclick="lightOn()">On</button>
然后是一点JavaScript:
and then a bit of JavaScript:
function lightOn(){
$("#lightOn").addClass("active");
$("#lightOff").removeClass("active");
socket.emit("setting", {"light":"on"});
}
当我点击按钮时出现错误:
When I click on the button I get the error:
Uncaught TypeError:lightOn不是函数
Uncaught TypeError: lightOn is not a function
任何想法为什么这不起作用?
Any idea why this won't work?
谢谢。
推荐答案
问题是你给你的元素相同的id:lightOn
。在此范围内 lightOn
是影响函数的元素(阅读更多内容)。
The problem is you give to your element the same id : "lightOn"
. In this scope lightOn
is the element, which shadows the function (read more).
一个简单的解决方案是为元素提供不同的id或不同的名称函数。
A simple solution would be to give a different id to the element or a different name to the function.
更好的方法是将脚本与HTML分开:
A better one would be to separate the script from the HTML:
<button type="button" class="btn btn-default" id="lightOn">On</button>
$(function(){
$('#lightOn').click(function() {
$("#lightOn").addClass("active");
$("#lightOff").removeClass("active");
socket.emit("setting", {"light":"on"});
});
});
这篇关于JavaScript错误:未捕获的TypeError:foo不是函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!