2010-03-17 6 views

Répondre

2
<span onclick="Clicked(this, 'SomeFunc', ['test', 123])">AAAA</span> 

... 

function Clicked(thisObject, funcName, params) 
{ 
// find an object with name funcName in default (window) scope 
var func = window[funcName]; 

// test that the object exist and that it's a function 
if (func && typeof func == "function") 
{ 
    // call the function with passed params 
    // passing 'thisObject' enables to use 'this' keyword within the called function 
    func.apply(thisObject, params); 

    // as an alternative you may call it without 'this' object 
    func.apply(null, params); 
} 
} 

function SomeFunc(text, num) 
{ 
    alert("text: " + text + ", number: " + num); 
} 
-1

Qu'est-ce que vous avez fonctionnerait, bien que, vous auriez besoin d'utiliser la fonction javascript eval pour évaluer la valeur une fois dans la fonction:

function Clicked(obj, functionText) 
{ 
    // do something with object.... 
    eval(functionText); 
} 

Sinon, s'il n'y a pas de paramètre, vous pouvez toujours passer la fonction elle-même:

onClick="Clicked(this, SomeFunction)" 

et mettre en œuvre comme ceci:

function Clicked(obj, func) 
{ 
    // do something with object... 
    func(); 
} 
+5

Notez qu'il serait très amateur d'utiliser 'eval' pour quelque chose comme ça. 'eval' a son usage (s?), ce n'est pas l'un d'entre eux. –

11
onClick = "Clicked(this, function() {SomeFunction('test')});" 


function Clicked (obj, functionToFire) 
{ 
    functionToFire(); 
} 
+0

ok à l'intérieur de la fonction Cliqué comment puis-je appeler la fonction SomeFunction en utilisant la fonction var passée en Clicked? – OutOFTouch

+0

@OutOFTouch Est-ce ce que vous demandez? – kemiller2002

+0

Oui, c'est ce que je demande, merci d'aider. – OutOFTouch

1
<script> 
function doSomeWork(arg1, arg2) 
{ 
    arg2(); 
} 
function displayThis(msg) 
{ 
    alert(msg); 
} 
doSomeWork("11",function(){ displayThis("123");}); 
</script> 
+0

Je pense que vous vouliez passer arg1 à arg2 comme: 'arg2 (arg1);' – jasongetsdown

-1

Ce ne pouvait pas être plus simple:

onClick = "function() { someFunction('test') }" 
Questions connexes