开发者

Executing a function passed as an argument in Javascript?

开发者 https://www.devze.com 2022-12-19 20:47 出处:网络
I\'m trying to write a generic function that wi开发者_如何学运维ll block out the UI while an AJAX call is made.What I\'m trying to do is have a function A run any other function passed in as an argume

I'm trying to write a generic function that wi开发者_如何学运维ll block out the UI while an AJAX call is made. What I'm trying to do is have a function A run any other function passed in as an argument. This is what I've got so far:

function blockWhileLoading(fn, msg)
{
  if (msg == null)
  {
    msg = 'Please wait while the next page is loaded...';
  }

  $.blockUI(
  {
    message: '<h1>' + msg + '</h1>',
    css:
    { 
      border: 'none', 
      padding: '15px', 
      backgroundColor: '#E3D9BA', 
      '-webkit-border-radius': '10px', 
      '-moz-border-radius': '10px', 
      color: '#4D2612'
    }
  }); 
  $('body').scrollLeft(0);

  setTimeout(function()
  {
    eval(fn);
    $.unblockUI();
  }, 1000);
}

Now when it comes time to eval the function, nothing seems to happen. Is eval not the correct way to force a function to run?


No, eval is used to turn a chunk of "string" into JavaScript code at runtime. Simply call fn(). It's a function reference.

This is what eval does:

var myalert = "alert('test');";
eval(myalert);

Equivalent to:

eval("alert('test');");


Just use fn();


If fn is being passed as an object and not a string, calling fn() should work.


Why not simply use:

fn();

Instead of eval.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号