Search code examples
jquerystringcommandexecute

run a jquery string command


I have a string that contains a jquery command How can I execute this string?

var myCommand = "$('#update').html('hello world!');";

Solution

  • You should not try to execute command from string, if you need to reuse them you should use a function:

    var myCommand = function(){
        $('#update').html('hello world!');
    }
    

    and then call it

    myCommand();
    

    Otherwise you must use eval() but it's not a best practice.

    Or you could use globalEval() which is better since it doesn't use eval()