0

我有 3 个页面加载相同的幻灯片。我试图通过将变量中的新内容从 javascript 传递到 html 元素来合并到一个页面。效果应该类似于ajax。传递的内容包括 html 标记。一切正常,但如果我在文本中包含撇号,它会失败。我可以通过使用锐角符号来解决;但想用撇号。这是标记和脚本的示例。Firefox、chrome 和 ie9 的结果相同。没什么大不了的,但我想了解它为什么会失败。有任何想法吗?

<?php
// Test of script passing content to <p> element
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en'>
    <head>
<script type="text/javascript">
function testSwap(text) {
    var text1=text;
    document.getElementById('test').innerHTML = text1;
}
</script>
</head><body>
<?php
$testtext="&lt;img style= &quot; float:left;margin:10px &quot; src= &quot;          http://www.w3schools.com/images/pulpit.jpg &quot; alt=&quot; Pulpit rock &quot; width=&quot;50&quot; height=&quot;60&quot; /&gt; &lt;span style=&quot;font-weight:bold;font-size:16px;text-decoration:underline&quot; &gt; Second Page Title &lt;/span&gt; : This page tells how we found our family&#180;s origins. This sample includes an image, a span element with styling, and a double line break. &lt;br /&gt;&lt;br /&gt; They all work. Unfortunately, the script fails if I include an apostrophe in this text so I use &#180; instead.&lt;br /&gt;&lt;br /&gt;Same result in firefox, chrome and ie9. Not a big deal, but I&#180;d like to understand why it fails. Any ideas?";


?>
<div><button type="button" onclick="testSwap('<?php echo $testtext; ?>')">Click Me!</button></div>

<p id='test'><span style='font-weight:bold;font-size:16px;text-decoration:underline'>My Main Page Title:</span>
The pages are in a genealogy site with our family&#39;s history. Main page introduces site and describes content<br /><br />Other two pages use same slide show of family pictures, but have more detailed info.<br /><br />Menu currently directs to a new page and reloads the slideshow. I plan to use javascript to avoid the reload if user has it enabled.<br /><br />This sample demonstrates the idea. Click on the button for second page.
</p>

</body></html>
4

2 回答 2

2

使用htmlentities: http: //php.net/manual/en/function.htmlentities.php

onclick="testSwap('<?php echo htmlentities($testtext); ?>')"

$testtext的是什么,里面有引号,对吗?如果是这样,htmlentities将把引号变成一个&#039;(或者&#34;如果它是一个双引号),它不会破坏testSwaponclick。

编辑:对不起,我完全改变了我的答案。改为使用htmlentities(之前是 urlencode)。

于 2013-03-15T23:12:40.477 回答
0

在页面呈现为 HTML 之前,PHP 标记会被标记内的表达式结果替换。因此,由于您<?php echo $testtext; ?>在单引号内,因此渲染后这些引号会出现问题。

您可以在字符串中使用反斜杠转义引号,这样当它以 HTML 呈现时,它会正确显示。

于 2013-03-15T23:13:43.047 回答