如何使用onclick来编辑innerHTML

时间:2015-07-23 16:07:17

标签: javascript html onclick innerhtml

所以在导航javascript文件中,我有这个,它有 onclick 事件属性来加载新页面:

function NAVLOAD()  {
    // Runs when you load page.
    document.getElementById("main nav").innerHTML = '<table class = "navbar"><tr>'+
    '<th onclick = "goTo("main_page")"> Home </th>'+
    '<th onclick = "goTo("archive")"> Archive </th>'+
    '<th onclick = "goTo("about")"> About </th>'+
    '<th  onclick = "goTo("faq")"> FAQ </th>'+
    '<th  onclick = "goTo("fanart")"> Fanart! </th>'+
    '</tr>'+    
    '<tr><td class = "spacer"></td></tr></table>';
}

function goTo(page) {
    window.location.assign(""+page+".html");
}

并且,使用它的HTML代码如下所示:

<html> <!-- Stuff -->
<body onload = "NAVLOAD();"> <div id = "main">
    <!-- Stuff -->

    <script src = "HTL_navigation_script.js"></script>
    <div id = "main nav" class = "comic"></div>
<!-- Some other stuff --> </body></html>

导航表显示正确,但点击它时链接不执行任何操作! 但是,当我在HTML文件中放入 NAVLOAD()函数中的HTML时,只从文件中导入 goTo()方法,链接确实有效!这有什么不对?

1 个答案:

答案 0 :(得分:-1)

您需要在包含NAVLOAD()方法的JS文件中进行以下更正。将引号从双引号(&#34;&#34;)更改为单引号(&#39;&#39;),in为了做到这一点,你还必须添加转义字符(&#39; \&#39;)。

function NAVLOAD()  {
    // Runs when you load page.
    document.getElementById("main nav").innerHTML = '<table class = "navbar"><tr>'+
    '<th onclick = "goTo(\'main_page\')"> Home </th>'+
    '<th onclick = "goTo(\'archive\')"> Archive </th>'+
    '<th onclick = "goTo(\'about\')"> About </th>'+
    '<th  onclick = "goTo(\'faq\')"> FAQ </th>'+
    '<th  onclick = "goTo(\'fanart\')"> Fanart! </th>'+
    '</tr>'+    
    '<tr><td class = "spacer"></td></tr></table>';
}

希望有所帮助:)