开发者

How to do a Proper Escape of this Function?

I have a DIV tag generated from jQuery that goes like this:

$('#results')
 .append('<DIV id='
 + A.pid
 + ' onmouseover=function(){google.maps.event.trigger(marker, 'mouseover');};><H3>'
 + A.name
 + '</H3></DIV>');

Firebug is giving me an error "missing ) argument after list" as it does not recognise the ) immediately after 'mouseover'.

Doing a \'mouseover\' produces a syntax error upon mouseover of the DIV. The syntax error reads: function(){google.maps.event.trigger(marker, and a look at the generated DIV shows:

<div id="1" 'mouseover');};="" onmouseover="function(){google.maps.event.trigger(marker,">

Doing a "mouseover" produces a blank document.

How do I do a proper escape for this function?

UPDATE:

This should work:

$('#results')
 .append('<DIV id='
 + A.pid
 + ' onmouseover=\"function(){google.maps.event.trigger(marker, \'mouseover\');};\"><H3>'
 + A.name
 + '</H开发者_如何学C3></DIV>');

I need to put escaped double quotes for the function and escaped single quotes for the argument.


You are putting data in JS in HTML in JS in HTML. Every level of encapsulation there requires a string escape, otherwise out-of-band characters will cause errors and possibly security holes. The human brain is not good at keeping track of multiple nested levels of string encapsulation.

So use jQuery's element creation shortcuts to set attributes on the new div, and the event handling features to add the listener to it, instead of messing around with ugly and unsafe HTML string hacking:

var div= $('<div>', {id: A.pid}).append($('<h3>', {text: A.name}));
div.mouseover(function() {
    google.maps.event.trigger(marker, 'mouseover');
});
$('#results').append(div);


You need to put " around the values of your html attributes. Otherwise the browser thinks the attribute ends at the next whitespace and that is exactly right after the (marker, part.

$('#results')
 .append('<DIV id="'
 + A.pid + '"'
 + ' onmouseover="function(){google.maps.event.trigger(marker, \'mouseover\');};"><H3>'
 + A.name
 + '</H3></DIV>');
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜