Reputation: 34424
i have a scenario where javascript function name needs to be decided at run time. For simplicity assume i have function name in javascript variable and now i want to create the function using variable value. I went thru the link Javascript - Variable in function name, possible? and tried the small code snippet
<HTML>
<HEAD>
<TITLE> New Document </TITLE>
</HEAD>
<script>
var temp1='at_26';
temp1: function() {alert("Inside 26"); }
</script>
<BODY>
<a href="javascript:window[at_26]()">Copy Text</a>
</BODY>
</HTML>
But when i click on hyperlink Copy Text it gives error saying Line: 1 Error: 'at_26' is undefined
Upvotes: 0
Views: 158
Reputation: 177940
var temp1='at_26';
window[temp1]=function() {alert("Inside 26"); return false}
and then
<a href="#" onclick="return window['at_26']()">Click</a>
or
<a href="#" onclick="return at_26()">Click</a>
should work
What I THINK you want since it does not pollute the global scope and is using a colon like in your example is this:
var myScope = {
"at_26":function() {alert("Inside 26"); return false}
}
using
<a href="#" onclick="return myScope.at_26()">Click</a><br />
Upvotes: 2
Reputation: 66663
There were multiple issues in your code. A corrected version will be like:
<script>
window['at_26'] = function() {alert("Inside 26"); };
</script>
<BODY>
<a href="javascript:window['at_26']()">Copy Text</a>
</BODY>
Upvotes: 1