2

I am creating a jquery function, but i have a problem passing some vars to my function. This is what i am tring to do, i resumed my code below:

var func = "appendTo";
var myid = "thisismyid";
var element = "div";
$("<"+element+"/>"{if(myid != ''){ id:myid}}).func($elem);

There's a way to do that? This is the only working code that i can get:

$("<"+element+"/>").appendTo($elem);

Thank you in advance.

asked Oct 24, 2013 at 23:52

3 Answers 3

1

You could do something like this:

$("<"+element+"/>"), { id: myid ? myid : null})[func]($elem);
answered Oct 24, 2013 at 23:57
Sign up to request clarification or add additional context in comments.

Comments

1

The second parameter when creating an element is an object. You cannot break an object with an if statement. You can however use a ternary to achieve the same results:

var func = "appendTo";
var myid = "thisismyid";
var element = "div";
$("<"+element+"/>", {id: (myid != '' ? myid : '') }).func($elem);
answered Oct 24, 2013 at 23:59

Comments

1

I fixed the code using the following:

$("<"+element+"/>",{id: (myid != '' ? myid : '')})[func]($elem);
Josh Crozier
242k56 gold badges401 silver badges316 bronze badges
answered Oct 25, 2013 at 0:19

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.