首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用javascript将html插入div

使用javascript将html插入div
EN

Stack Overflow用户
提问于 2012-09-17 15:00:44
回答 3查看 6.1K关注 0票数 3

在使用javascript更新div时,我遇到了问题。

代码语言:javascript
复制
<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做一些操作?

提前感谢!

EN

回答 3

Stack Overflow用户

发布于 2012-09-17 15:04:25

Unterminated string literal通常意味着您尝试这样做:

代码语言:javascript
复制
var str = "Blah blah blah
  more blah that should be part of the string
  even more blah.";

您不能在JavaScript中这样做,您必须结束字符串并追加下一行:

代码语言:javascript
复制
var str = "Blah blah blah\n"
  +"more blah that should be part of the string\n"
  +"even more blah.";

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

代码语言:javascript
复制
var str = "Blah blah blah\
  more blah that should be part of the string\
  even more blah.";

还请注意,您要修改的元素尚未定义。要么确保您要修改的<div>位于<script>之前,要么推迟脚本或其内容(window.onload或类似内容)。

票数 5
EN

Stack Overflow用户

发布于 2012-09-17 15:04:44

看起来文本中有回车。

如果你有机会的话,也许在分配之前把这些换成休息。

代码语言:javascript
复制
stringWithReturnsIn.replace(/[\n\r]/g, '<br />');

如果希望保留返回,则为br。

代码语言:javascript
复制
stringWithReturnsIn.replace(/[\n\r]/g, ' ');
票数 0
EN

Stack Overflow用户

发布于 2012-09-17 15:07:57

问题可能是你正在使用的花哨引号(‘and’)。试着用“”代替它们。

将HTML插入到这样的页面通常不是很好的做法,因为解析错误的数量和潜在的XSS漏洞。考虑使用document.createElement()创建内部元素,并在子元素中追加文本内容。它有点冗长,但如果结构保持不变,则修改起来就更无缝了。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/12462021

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档