ajmajmajma
ajmajmajma

Reputation: 14216

Jquery, Escaping url with variable

trying to escape and html for appending in jquery with adding a dynamic variable that i am bringing in with ajax and I seem to not be able to get the escaping correct. Here is what I have -

$("<div><div class='presiImg' style='background: url(/\'/gleam\/public\/images\/itPrecedents\/" + keep.logo + "');'></div></div>").appendTo(".myDiv');

I am unsure how to escape this correctly so I can use the variable. Thanks.

Upvotes: 0

Views: 224

Answers (2)

Dave
Dave

Reputation: 10924

You've got a couple issues here:

  1. You're escaping the forward slashes in your URL and that is not necessary
  2. You are using inconsistent quotes in your .appendTo()

As a suggestion, when I append raw HTML using JS/jQuery I try to use the single-quote and the JavaScript quote, and then use the double-quotes in the HTML. For me it is just easier to see that way. Also, the single-quote in the CSS url is not required, and is perhaps confusing the matter.

Anyway, if you change your line to the following it will work:

$('<div><div class="presiImg" style="background: url(\'/gleam/public/images/itPrecedents/' + keep.logo + '\');"></div></div>').appendTo('.myDiv');

There is a runnable example below if you want to see it in action:

$(function() {
  
  var keep = { logo : "test.jpg" };
  $('<div><div class="presiImg" style="background: url(\'/gleam/public/images/itPrecedents/' + keep.logo + '\');"></div></div>').appendTo('.myDiv');
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="myDiv"></div>

Upvotes: 1

mplungjan
mplungjan

Reputation: 177684

try

$("<div />",{ 
 "class":"presiImg",
 "style":"background: url(/gleam/public/images/itPrecedents/"+keep.logo+")"
}).appendTo(".myDiv");

Upvotes: 1

Related Questions