javascript ReferenceError:使用 onclick 时未定义函数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13325067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
ReferenceError: function is not defined when using onclick
提问by Huy
I set up an anchor tag using javascript so that that onclick
, I call a function showSavingsEasterEgg
and pass it a value. The problem I am getting is that I'm not referencing my function correctly:
我使用 javascript 设置了一个锚标记,以便onclick
我调用一个函数showSavingsEasterEgg
并传递一个值。我遇到的问题是我没有正确引用我的函数:
ReferenceError: showSavingsEasterEgg is not defined
ReferenceError: showSavingsEasterEgg is not defined
I've tried moving the showSavingsEasterEgg
function into the showData
function to see if it solved the scoping problem, but it didn't.
我尝试将showSavingsEasterEgg
函数移到showData
函数中以查看它是否解决了范围界定问题,但没有解决。
Any tips
有小费吗
define(["jquery", "go/util", "underscore", "jqueryui/slider"], function ($, util,_) {
function showData(data) {
$('#item').append('<a class="savings_link" href="#" onclick=\'showSavingsEasterEgg('+data[key]['saving']+')\'> Savings');
}
function showSavingsEasterEgg(data){
console.log("SUccess");
console.log(data);
}
});
回答by Denys Séguret
Put the definition of showSavingsEasterEgg
directly in the global scope.
将 的定义showSavingsEasterEgg
直接放在全局范围内。
Here, it can't be found.
在这里,找不到。
You can do this :
你可以这样做 :
window.showSavingsEasterEgg = function (data){
console.log("SUccess");
console.log(data);
};
define(["jquery", "go/util", "underscore", "jqueryui/slider"], function ($, util,_) {
function showData(data) {
$('#item').append('<a class="savings_link" href="#" onclick=\'showSavingsEasterEgg('+data[key]['saving']+')\'> Savings');
}
});
回答by jAndy
Wondering why nobody suggested the most obvious, convenient and "best practice" way so far. You shouldn't use inline event handlingat all, do it unobtrusive.
想知道为什么到目前为止没有人提出最明显、最方便和“最佳实践”的方法。你根本不应该使用内联事件处理,不要引人注目。
$('#item').append($('<a>', {
'class': 'savings_link',
href: '#',
click: function(e) {
console.log("SUccess");
console.log(data);
}
}});
回答by Anoop
Make showSavingsEasterEgg global. you can call only globally accessible objects/references from html code.
使 showSavingsEasterEgg 全球化。您只能从 html 代码调用全局可访问的对象/引用。
window.showSavingsEasterEgg = function(data){
console.log("SUccess");
console.log(data);
}
回答by Rikki
You should know and understand what is the definition of "scope"
in any programming languages. Please move the function named "showSavingsEasterEgg"
out side of the parent function and it will work like a charm. It's because you defined it as a private member of the parent function.
您应该知道并理解"scope"
任何编程语言中的定义。请将名为的函数"showSavingsEasterEgg"
移出父函数,它会像魅力一样工作。这是因为您将其定义为父函数的私有成员。
Cheers
干杯