0

I need to use single qoute to wrap 2 valiables inside .html() method in jQuery. I want to know how to fix this ?

$("#mydiv").html('<a class="accset_chg_ressid" href="#" onclick="changeit(var1,var2);">Change Change it</a>');

var1 and var2 is none numeric variable, so it need single qoute to wrap it. But How to fix this ?

  • 2
    You can escape with \ __HOWEVER__ , don't have inline handlers inside HTML you add _especially_ since you're using jQuery so you have a crossbrowser `.click` method. Also, don't build HTML like that, either create it normally (using `$("$")` or `document.createElement`) or use proper templates. – Benjamin Gruenbaum Dec 17 '13 at 13:26
  • Could you please give me an example of $("$") method or the best way to do ? – user3104858 Dec 17 '13 at 13:28

2 Answers2

0

You can do it by just adding the escape \. Check below.

$("#mydiv").html('<a class="accset_chg_ressid" href="#" onclick="changeit(\'var1\',\'var2\');">Change Change it</a>');
A Paul
  • 8,113
  • 3
  • 31
  • 61
  • Hi, Thank you for your answer I actually have tried this , it works..but the comment above: Benjamin Gruenbaum said: this is not the best way to do. What should I do ? – user3104858 Dec 17 '13 at 13:33
0

You asked in the comment for a better way to do this, so here is one:

var $a = $("<a></a>").addClass("accset_chg_ressid").
                     attr("href","#").
                     click(function(e){// changeit should probably be here
                         return changeit(var1,var2); 
                     }).text("Change Change it");
//cache the reference later
$("#myDiv").empty().append($a);//add to the parent

Note that this way you have a reference to the element (for further manipulation, removal etc). You also don't have any 'string magic'.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
  • Thank you so much for answer. I want to know what is the reason I should not use inline method as you mentioned above ? – user3104858 Dec 17 '13 at 13:35
  • @user3104858 less string magic, actual context if you have a problem with the onclick handler, also see http://stackoverflow.com/questions/11737873/ (and a million other answers on the subject). Ever tried debugging an inline handler? Or changing the content of magic strings like that? – Benjamin Gruenbaum Dec 17 '13 at 13:37
  • This is very new knowlege for me. But thank you for this. Very useful. – user3104858 Dec 17 '13 at 13:43