使用JavaScript将HTML插入到div中

3
我使用JavaScript更新div时遇到了问题。
<script>
document.getElementById('advertisingBrandValues').innerHTML = "<p>The Mac is the most powerful   creative tool in the world, giving users unbridled potential to make everything from     bespoke family albums to industry-standard pop songs – iCreate is the key to unlocking that potential. Accessible, smart and authoritative, the iCreate brand thrives on the mantra ‘instruct, inform, inspire’, helping thousands of Mac users realise their creative ambitions.</p>";                   

</script>

<div id="advertisingBrandValues"></div>

我不断地收到如下错误提示:

未终止的字符串文字,并且它指示错误出现在第一个P标签处。

我需要对传递给innerHTML函数的HTML做些什么吗?

提前感谢!


除了一些花哨符号的乱码外,在Safari上没有任何问题。 - Jeffrey Sweeney
3个回答

5

未终止的字符串字面量通常意味着您尝试执行以下操作:

var str = "Blah blah blah
  more blah that should be part of the string
  even more blah.";

在JavaScript中无法这样做,你必须结束当前字符串并拼接下一行:

var str = "Blah blah blah\n"
  +"more blah that should be part of the string\n"
  +"even more blah.";

或者您可以转义换行符(不确定这是否完全标准):

var str = "Blah blah blah\
  more blah that should be part of the string\
  even more blah.";

请注意,您尝试修改的元素尚未定义。请确保您要修改的 <div> 先于 <script> 出现,或者推迟脚本或其内容(window.onload 或类似方法)。


好的,谢谢。我给出的例子实际上并没有包括我真正传递的内容。事实上,我使用的数据中有很多换行符。是否有 PHP 中可以用来转义换行符的函数?我说 PHP 函数是因为我实际上正在将一个 PHP 变量传递给 innerHTML 函数。 - richelliot
要将(几乎)任何变量从PHP传递到JavaScript,请参见json_encode - Niet the Dark Absol
从标准的角度来看,最后一段代码还不错,尽管它与第二段代码并不完全相同——它没有添加新行。 - VisioN

0

看起来文本中有回车符。

如果有机会的话,在分配之前可能要将其替换为换行符。

stringWithReturnsIn.replace(/[\n\r]/g, '<br />');

如果你想保留换行符,可以使用br标签

stringWithReturnsIn.replace(/[\n\r]/g, ' ');

0

问题可能是您正在使用的花式引号(‘和’)。尝试用'替换它们。

像这样将HTML插入页面通常不是好的做法,因为会产生大量解析错误和潜在的XSS漏洞。考虑使用document.createElement()创建内部元素,并在子元素中添加文本内容。这样做可能会更冗长一些,但是如果结构保持不变,则修改起来更加无缝。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接