我正试图在这个javascript变量中存储一个HTML块,
var element = <div class="MMinfoboxRoot">
<div class="MMinfoboxaddress">
<div>
<span class="MMrecordName">leicester
</span>
<br>
<span class="MMdaySpan MMdaySpanTitle">Opening Times
</span>
<br>
<br>
<span class="MMdaysRoot MMdaysmonday">
<span class="MMdaySpan">Monday:
</span>
<span class="MMdayHoursSpan">9am - 8pm
</span>
</span>
<br>
<span class="MMdaysRoot MMdaystuesday">
<span class="MMdaySpan">Tuesday:
</span>
<span class="MMdayHoursSpan">9am - 8pm
</span>
</span>
<br>
<span class="MMdaysRoot MMdayswednesday">
<span class="MMdaySpan">Wednesday:
</span>
<span class="MMdayHoursSpan">9am - 8pm
</span>
</span>
<br>
<span class="MMdaysRoot MMdaysthursday">
<span class="MMdaySpan">Thursday:
</span>
<span class="MMdayHoursSpan">9am - 8pm
</span>
</span>
<br>
<span class="MMdaysRoot MMdaysfriday">
<span class="MMdaySpan">Friday:
</span>
<span class="MMdayHoursSpan">9am - 8pm
</span>
</span>
<br>
<span class="MMdaysRoot MMdayssaturday">
<span class="MMdaySpan">Saturday:
</span>
<span class="MMdayHoursSpan">9am - 6pm
</span>
</span>
<br>
<span class="MMdaysRoot MMdayssunday">
<span class="MMdaySpan">Sunday:
</span>
<span class="MMdayHoursSpan">11am - 5pm
</span>
</span>
<br>
<br>
<br>
<div class="links">
<strong style="color: rgb(0, 0, 102);">Get directions
</strong>
<form onsubmit="GetDirectionsFromInfoBox( this, 0 ); return false;" id="directionsForm-1" method="post" action="" class="directions">
<label for="infoboxDir1">From
<input type="text" id="infoboxDir1" value="birstall" class="text">
</label>
<input type="image" class="map-submit" src="css/winter-sale-2010/images/multimap/go-button.gif">
</form>
<a class="go-to-location" onclick="ZoomToLocation( 0 ); return false;" href="#">Zoom to this location
</a>
</div>
</div>
</div>
</div>
然而,它会抛出js错误,说出无法使用的字符串。我该怎么办呢?
答案 0 :(得分:8)
最后需要一个反斜杠,用于跨越多行的字符串和一些引号来整体封装它,如下所示:
var element = '<div class="MMinfoboxRoot"> \
<div class="MMinfoboxaddress"> \
....';
同样,@ T.J.指出如果您在字符串中有任何'
(或您使用的任何包装引号),请务必使用转义表单,例如此处\'
答案 1 :(得分:8)
您可以将其存储在ID'ed脚本标记内:
<html>
<head>
<script id="htmlTemplate" type="text/x-tmpl">
This <h1>is</h1> templated.
</script>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript">
$(document).ready(
function() {
$('#2nd').html($('#htmlTemplate').text());
}
);
</script>
</head>
<body>
<div id="1st">First div</div>
<div id="2nd">Second div</div>
</body>
</html>
顺便说一下,有一个使用这种方法的jQuery插件:http://api.jquery.com/category/plugins/templates/
答案 2 :(得分:1)
首先,您需要使用'
或"
来封装字符串文字。
此外,您需要添加\
添加每行的结尾,否则JavaScript将无法识别多行字符串。
这样的事情会起作用:
var element = '<div class="MMinfoboxRoot">\
<div class="MMinfoboxaddress">\
<div>\
<span class="MMrecordName">leicester\
</span>'
确保转义该字符串中的任何'
,如果您想要换行符,则需要在尾随\n
前面添加\
。
答案 3 :(得分:1)
这是一个我一直在使用的方便工具 http://htmltojavascript.com
它自动创建一个html标签列表,保持
缩进。我相信使用join更好
与某些成员建议的连接相比。
我已经在该网站上运行了您的代码 它有效。