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
Arianna Hajar DelBen
539 bronze badges
3 Answers 3
You could do something like this:
$("<"+element+"/>"), { id: myid ? myid : null})[func]($elem);
answered Oct 24, 2013 at 23:57
Jason P
27k3 gold badges34 silver badges45 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
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);
Comments
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
Arianna Hajar DelBen
539 bronze badges
Comments
lang-js