JQuery attr () accelerating ampersands

So, I am trying to set the src attribute of an image dynamically using javascript as follows:

var url = 'query.php?m=traffic&q=getgraph&id='+pipeId+'&start=-3h';
console.log(url);
$('#3h').attr('src',url);

The problem is that it displays like this: query.php?m=traffic&q=getgraph&id=1&start=-3hin the console, the actual src set for image element # 3h isquery.php?m=traffic&q=getgraph&id=1&start=-3h

And then, of course, this will not work. How to avoid jQuery attr () method character exception? Any other suggestions on how I should achieve my goal are also welcome.

+5
source share
5 answers

If it does not work, this is not because the ampersands are shielded. As an attribute in an HTML element, all XML elements must be escaped:

--+-------
< | &lt;
> | &gt;
" | &quot;
& | &amp;

, index.php?foo=bar&buzz=baz, , a , :

<a href="index.php?foo=bar&amp;buzz=baz

href : index.php?foo=bar&buzz=baz

, .

+3

, , , , HTML4.

$('#3h') // invalid for HTML4

, , h3

$('#h3') // valid ID for HTML4
+2

escape , .

 $('#3h').attr('src', escape(url));

unescape($('#3h').attr('src'))
0

jQuery JavaScript/DOM:

document.getElementById('3h').src = url;

-1

All Articles