开发者

jquery dynamic function

开发者 https://www.devze.com 2023-02-22 15:10 出处:网络
I just need the logic and understanding on how I can do this. The problem: I have several functions that are very similar but I want to create/call th开发者_JS百科e dynamically

I just need the logic and understanding on how I can do this.

The problem:

I have several functions that are very similar but I want to create/call th开发者_JS百科e dynamically

Example:

$(document).ready(function() {         
    function foo() {
        $("#foo_elem").toggle(true).attr('required', true);
        alert('This is foo');
    }

    function bar() {
        $("#bar_elem").toggle(true).attr('required', true);
        alert('This is bar');
    }
});

How can I pass in foo/bar to create the function? Pseudo code

$(document).ready(function() { 
    // would pass foo/bar to this?        
    $($x)(function() {
        $("#"+$(this)+"_elem").toggle(true).attr('required', true);
        alert('This is '+$(this));
    });
});


You want to dynamically call foo or bar?

function callMethod(method)
{
     method();
}

callMethod(foo); // foo is the symbol for your method
callMethod(bar); // etc

At a high level. In your instance, though, you're asking to use that symbol as just a variable in your selector:

function callMethod(elementPrefix)
{
    $('#' + elementPrefix+ '_elem').toggle(true).attr('required', true);
    alert('This is ' + elementPrefix);
}

If you want to use it both as a string value, and the method name, you can eval the symbol to get the method:

var methodName = 'foo';
var text = 'This is ' + methodName; // This is foo
var method = eval('(' + methodName + ')');
method(); // calls foo()


I'm not sure if I understood your question fully, but do you want to dynamically create a function based on some arguments? If so, you could do something like this:

function make_func(x) {
  return function() {
    $("#"+x+"_elem").toggle(true).attr('required', true);
    alert('This is '+x);
  };
}

Then make_func('foo') would return a function which is equivalent to the function foo in your original example.

0

精彩评论

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