jquery - 在添加内容时转义引号问题

时间:2012-06-08 19:49:40

标签: javascript jquery escaping

我正在尝试使用以下代码段:

$('#thirdPartyCheckoutButtons').prepend('<a href="https://www.resellerratings.com" onclick="window.open("https://seals.resellerratings.com/landing.php?seller=myID","name","height=760,width=780,scrollbars=1"); return false;"><img style="border:none;" src="//seals.resellerratings.com/seal.php?seller=myID" oncontextmenu="alert("Copying Prohibited by Law - ResellerRatings seal is a Trademark of All Enthusiast, Inc."); return false;" /></a><img src="https://www.myurl.com/hdsd834k.png"  style="float: left;margin-left: 180px;">');

它根本没有显示..我尝试了很多引用差异,我不明白!

2 个答案:

答案 0 :(得分:2)

内部 - 内部双引号会破坏您的onclick属性值。用单引号替换它们并将它们转义。

...onclick="window.open(\'https://seals.resellerratings.com/landing.php?seller=myID\',\'name\',\'height=760,width=780,scrollbars=1\'); return false;"...

同样的事情发生在oncontextmenu事件上,执行相同的修复。

...oncontextmenu="alert(\'Copying Prohibited by Law - ResellerRatings seal is a Trademark of All Enthusiast, Inc.\'); return false;" />...

完整代码:

$('#thirdPartyCheckoutButtons').prepend('<a href="https://www.resellerratings.com" onclick="window.open(\'https://seals.resellerratings.com/landing.php?seller=myID\',\'name\',\'height=760,width=780,scrollbars=1\'); return false;"><img style="border:none;" src="//seals.resellerratings.com/seal.php?seller=myID" oncontextmenu="alert(\'Copying Prohibited by Law - ResellerRatings seal is a Trademark of All Enthusiast, Inc.\'); return false;" /></a><img src="https://www.myurl.com/hdsd834k.png"  style="float: left;margin-left: 180px;">');​

答案 1 :(得分:2)

prepend()函数中的字符串由单引号分隔。这意味着您在该字符串中键入的每个引号都必须由a转义。但是,这不是你的问题。您的问题在于无效的HTML。这就是你所拥有的:

$('#thirdPartyCheckoutButtons').prepend('<a href="https://www.resellerratings.com" onclick="window.open("https://seals.resellerratings.com/landing.php?seller=myID","name","height=760,width=780,scrollbars=1"); return false;"><img style="border:none;" src="//seals.resellerratings.com/seal.php?seller=myID" oncontextmenu="alert("Copying Prohibited by Law - ResellerRatings seal is a Trademark of All Enthusiast, Inc."); return false;" /></a><img src="https://www.myurl.com/hdsd834k.png"  style="float: left;margin-left: 180px;">');

如果您发现所有HTML属性值都用双引号分隔。但是,在onclick =“”事件中,您再次使用双引号。您可以使用ESCAPED单引号来解决此冲突。你的oncontextmenu =“”事件也有同样的问题。

$('#thirdPartyCheckoutButtons').prepend('<a href="https://www.resellerratings.com" onclick="window.open(\'https://seals.resellerratings.com/landing.php?seller=myID\',\'name\',\'height=760,width=780,scrollbars=1\'); return false;"><img style="border:none;" src="//seals.resellerratings.com/seal.php?seller=myID" oncontextmenu="alert(\'Copying Prohibited by Law - ResellerRatings seal is a Trademark of All Enthusiast, Inc.\'); return false;" /></a><img src="https://www.myurl.com/hdsd834k.png"  style="float: left;margin-left: 180px;">');

将来避免此问题的最简单方法是在jQuery函数调用之外构建字符串(HTML),然后将字符串作为变量传递。