English 中文(简体)
与 jQuery 一起执行动态传递的函数调用
原标题:Executing dynamically passed function call with jQuery

我有此函数呼叫作为字符串通过 :

var dcall = "tumbsNav(1)";

能否像 SQL 的 Exec 那样动态执行此操作?

exec(dcall)
最佳回答

不论你们在那里重新储存,

var dcall = "tumbsNav(1)";

您可以转而存储

var dcall = function() {
   return tumbsNav(1);
};

无论你在哪里叫它, 而不是叫它,而不是叫它

eval(dcall);

您可以拨打

dcall();

这唯一行不通的情况是当 tumbumbsNav va vunc = =. 被调用时没有定义。 那么您必须保存字符串。 如果字符串完全在您控制之下, 那么就不会有安全洞, 但是要了解@ Porco 所提到的所有问题 。

正如Kolink提到的那样,如果在指派 tumburbsNav 时没有定义它带有一个可以调用 tumbs 的包裹式匿名功能,我的例子就不会造成问题。

var dcall = tumbsNav, darg = 1;
// later in the code, you can call
dcall(darg) ;
问题回答

eval 是等效的, 但你不应该使用它 。

相反,通过这样的函数:

var dcall = function() {tumbsNav(1);};

然后称它为:

dcall();

使用 eval( 调用) 。

正如其他人提到的,评估被认为是不良的做法。

1) 不当使用可使你的代码易受注射攻击。

2) 维护代码变得更加困难(没有行号,不能使用调试工具)

3) 执行更慢(浏览器可编译)

(4) 打击范围无法预测。

但是,如果你能理解所有这些,那么评估会很有帮助。





相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签