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:
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.
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.
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. you can call only globally accessible objects/references from html code.
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. 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.
Cheers
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.