admin管理员组文章数量:1356863
Say i am using some of the html5 data chars and i want to know what function to call when say something is pleted for a certain div tag.
so my data would look like
data-callback='jsAPI.aSubset.desiredFunction'
How would i convert that callback (a string) into the function that i want to call. A simple global function such as
data-callback='_myfunction'
<script>
function _myfunction() { alert("yes my function"); }
$("div").click(function() {
var fn = $(this).data("callback");
if (typeof fn === 'function') {
fn();
}
})
</script>
but how do i do it with the previous one jsAPI.aSubset.desiredFunction
Thanks
Say i am using some of the html5 data chars and i want to know what function to call when say something is pleted for a certain div tag.
so my data would look like
data-callback='jsAPI.aSubset.desiredFunction'
How would i convert that callback (a string) into the function that i want to call. A simple global function such as
data-callback='_myfunction'
<script>
function _myfunction() { alert("yes my function"); }
$("div").click(function() {
var fn = $(this).data("callback");
if (typeof fn === 'function') {
fn();
}
})
</script>
but how do i do it with the previous one jsAPI.aSubset.desiredFunction
Thanks
5 Answers
Reset to default 4Sounds like a great use case for the dreaded eval()
.
I would do something like:
var fnString = "jsAPI.aSubset.desiredFunction";
var fn = eval(fnString);
if (typeof(fn) === "function") {
fn.apply();
Using square brackets only works if you have no .
chain.
Try this instead:
var elms = fn.split(".");
var curr = window;
var nxt;
while(nxt = elms.shift()) curr = curr[nxt];
curr();
Use square brackets...
jsAPI.aSubset[fn]();
so...
if (typeof jsAPI.aSubset[fn] === 'function') {
jsAPI.aSubset[fn]();
}
You might want to just use Function("functionstring")
. The Function function returns a function from a string.
Try window[fn]()
if the function is defined in the global scope.
本文标签: String to function javascriptStack Overflow
版权声明:本文标题:String to function javascript - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743944200a2566104.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论