String issue with Javascript adding dynamic HTML
I'm using PHP to generate a Javascript button that adds in a checkbox and some other HTML.
What is the proper way to escape these characters to include them in an onclick event?
I saw it suggested to convert ' and " to the ascii values, but that doesn't seem to have helped.
$tempOutput = "<a href='temp.txt'>\"Happy\"</a>";
$tempOutput = str_replace("'", "'", $tempOutput);
$tempOutput = str_replace('"', """, $tempOutput);
just results in this if you echo the string right before use:
<a href='temp.txt'>"Happy"</a>
and this if you inspect the page element:
<a onclick="
var divTag = document.createElement('div');
divTag.innerHTML = '<a href='temp.txt'>"Happy"</a>';
document.getElementById('extraDiv').appendChild(divTag) ;
">test</a>开发者_如何学Go;
I've also tried just appending to the extradiv's innerHTML but no success there either.
I mostly use PHPs rawurlencode() and Javascript's unescape():
<?php
$tempOutput = '<a href="temp.txt">'.htmlentities('"Happy"').'</a>';
?>
<a onclick="
var divTag = document.createElement('div');
divTag.innerHTML = unescape('<?php echo rawurlencode($tempOutput);?>');
document.getElementById('extraDiv').appendChild(divTag) ;
">test</a>
<div id="extraDiv"></div>
This will also avoid errors with other chars, e.g. linebreaks.
Escape like this
$tempOutput = str_replace(array("'",'"'), array("\'",'"'), $tempOutput);
use html_entity_decode
精彩评论