[英]ReferenceError: function is not defined when using onclick
I set up an anchor tag using javascript so that that onclick
, I call a function showSavingsEasterEgg
and pass it a value. 我使用javascript设置了一个锚标签,以便
onclick
,我调用一个函数showSavingsEasterEgg
并传递一个值。 The problem I am getting is that I'm not referencing my function correctly: 我得到的问题是我没有正确引用我的功能:
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);
}
});
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');
}
});
Wondering why nobody suggested the most obvious, convenient and "best practice" way so far. 想知道为什么没有人提出迄今为止最明显,最方便和“最佳实践”的方法。 You shouldn't use inline event handling at all, do it unobtrusive.
你根本不应该使用内联事件处理 ,不要引人注目。
$('#item').append($('<a>', {
'class': 'savings_link',
href: '#',
click: function(e) {
console.log("SUccess");
console.log(data);
}
}});
Make showSavingsEasterEgg global. 使showSavingsEasterEgg全局化。 you can call only globally accessible objects/references from html code.
您只能从html代码中调用全局可访问的对象/引用。
window.showSavingsEasterEgg = function(data){
console.log("SUccess");
console.log(data);
}
You should know and understand what is the definition of "scope"
in any programming languages. 您应该了解并理解任何编程语言中
"scope"
的定义。 Please move the function named "showSavingsEasterEgg"
out side of the parent function and it will work like a charm. 请将名为
"showSavingsEasterEgg"
的函数移出父函数的一侧,它将像魅力一样工作。 It's because you defined it as a private member of the parent function. 这是因为您将其定义为父函数的私有成员。
Cheers 干杯
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.