在innerHTML命令中遇到很多HTML代码

时间:2013-12-18 23:31:16

标签: javascript html

我目前正在一个名为GeneralJS的JS文件中编写一个简单的JS函数 应该执行一个滑动条。该函数看起来像这样

function LoadSideBar() { document.getElementById("sideBarDiv").innerHTML = "<div data-role="panel" data-position="left" data-position-fixed="false" data-display="reveal" id="nav-panel" data-theme="a">
        <a href="index.html" data-role="button" data-theme="e" data-icon="home" > 1</a><br/>
        <a href="NewTask.html" data-role="button" data-theme="b" data-icon="plus" > 2</a><br/>
        <a href="JoinGroups.html" data-role="button" data-theme="b" data-icon="search" > 3</a><br/>
        <a href="Groups.html" data-role="button"  data-theme="b" data-icon="grid" > 4</a><br/>
        <a href="Settings.html" data-role="button"  data-theme="b" data-icon="gear" > 5</a><br/>
        <a href="" data-role="button"  data-theme="b" data-icon="info" > 6 </a><br/>
        <a href="" data-role="button"  data-theme="b" data-icon="arrow-r" > 7 Us </a><br/>
        <a href="" data-role="button"  data-theme="b" data-icon="minus" > 8 </a>
            </div>";
}

HTML执行代码为<script src="GeneralJS.js"> </script> <script> LoadSideBar() </script>

问题似乎是.innerHTML =我在引号中放了很多HTML代码,因为当我将HTML代码更改为"<h1> Hi </h1>"时,一切正常。有人有线索吗?

1 个答案:

答案 0 :(得分:2)

问题是你要用双引号(")定义这个长字符串,它也在你试图放入字符串的html代码中,所以字符串在首先在html代码中引用。通过使用单引号(')定义字符串可以很容易地解决这个问题,因为html代码不使用它们:

function LoadSideBar() { document.getElementById("sideBarDiv").innerHTML = '<div data-role="panel" data-position="left" data-position-fixed="false" data-display="reveal" id="nav-panel" data-theme="a"> <a href="index.html" data-role="button" data-theme="e" data-icon="home" > 1</a><br/> <a href="NewTask.html" data-role="button" data-theme="b" data-icon="plus" > 2</a><br/> <a href="JoinGroups.html" data-role="button" data-theme="b" data-icon="search" > 3</a><br/> <a href="Groups.html" data-role="button" data-theme="b" data-icon="grid" > 4</a><br/> <a href="Settings.html" data-role="button" data-theme="b" data-icon="gear" > 5</a><br/> <a href="" data-role="button" data-theme="b" data-icon="info" > 6 </a><br/> <a href="" data-role="button" data-theme="b" data-icon="arrow-r" > 7 Us </a><br/> <a href="" data-role="button" data-theme="b" data-icon="minus" > 8 </a> </div>'; }