1

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

var myCommand = "$('#update').html('hello world!');";
1
  • Why do you have a string that has JavaScript code in it? Where is it coming from? Commented Sep 20, 2011 at 15:57

2 Answers 2

1

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()

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.