簡體   English   中英

使用javascript將html插入div

[英]insert html into div using javascript

我在使用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?

提前致謝!

Unterminated string literal通常意味着您嘗試執行以下操作:

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或類似)

看起來文本中有回車符。

如果你有機會,可以在分配之前交換那些休息

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

如果你想保留回報,則為br

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

問題可能是你正在使用的花哨報價('和')。 嘗試用'替換它們。

由於解析錯誤的數量和潛在的XSS漏洞,將HTML插入到頁面中通常不是一種好的做法。 考慮使用document.createElement()創建內部元素,並在子元素中附加文本內容。 它有點冗長,但假設結構保持不變,可以更加無縫修改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM