![](/img/trans.png)
[英]how do i paste and assign string to javascript variable, if string is weird?
[英]How do I assign a HTML string over multiple lines in Javascript?
我必須通過以下Javascript代碼分配HTML字符串。 但是,只有將所有HTML放在一行中,這才有可能。
這有效:
var assignedhtml = "<div> <p>It's the most beautiful thing I've seen in my life </p> <p> It's watermalone </p> </div>"
這不起作用:
var assignedhtml = "<div>
<p>It's the most beautiful thing I've seen in my life </p>
<p> It's watermalone </p>
</div>"
問題是我的html代碼行太多。 過去,我已經單獨刪除了所有\\n
(換行符)字符。 是否有一種更簡單的方法來實現我想要的變量分配,而不必單獨瀏覽各行並刪除換行符?
即,我想像上面第二種情況一樣將html代碼保留在右側,但是在將其分配給變量之前先刪除換行符。
例如,它不等同於PHP的heredoc,但是您可以添加反斜杠來避免硬性回報:
var assignedhtml = "<div>\
<p>It's the most beautiful thing I've seen in my life </p>\
<p> It's watermalone </p>\
</div>";
這是一個工作示例: http : //jsfiddle.net/9W6BS/
您可以這樣做:
var assignedhtml = '<div>' +
'<p>It\'s the most beautiful thing I've seen in my life</p>' +
'<p>It\'s watermelon</p>' +
'</div>';
另一種變體-在第and行使用'\\'符號
有效的代碼示例
var assignedhtml = "<div>\
<p>It's the most beautiful thing I've seen in my life </p>\
<p> It's watermalone </p>\
</div>"
還需要注意的是,某些工具(例如webStorm或PhpStorm)允許在普通模式下編輯此類注入(Alt + Enter-編輯HTML片段)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.