0

I have to call Jquery functions using a variable value.

Let consider below scenario:

               var func = "append";   
               $(document).func("<div>Append Welcome</div>");
               func = "prepend";   
               $(document).func("<div> Prepend Welcome</div>");
               func = "html";   
               $(document).func("<div> Insert Html Welcome</div>");         

I can use if and else but is there any way to achieve as above.

Is this a good way to do or simply use if and else?

1
  • 1
    Try $(document)[func]("<div>Append Welcome</div>"); Commented Aug 27, 2015 at 13:42

2 Answers 2

3

Functions can be accessed using [] syntax, just like regular properties of an object:

var func = "append";   
$(document)[func]("<div>Append Welcome</div>");
func = "prepend";   
$(document)[func]("<div> Prepend Welcome</div>");
func = "html";   
$(document)[func]("<div> Insert Html Welcome</div>");      
Sign up to request clarification or add additional context in comments.

Comments

2

You can call a function using a variable name with bracket notation: https://jsfiddle.net/leojavier/mw4hm5ma/

var app = {
    alert : function(message){
    alert(message)
    }
}
var funcName = "alert"

app[funcName]('this is a message')

I'm creating an object with a method inside... then I can use the variable value as a name for that function ex Object[variable](arguments)

I hope this helps...

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.