Javascript 如何让onclick在已编辑的innerHTML中工作

Javascript 如何让onclick在已编辑的innerHTML中工作,javascript,html,onclick,innerhtml,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")"> Hom

因此,在导航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");
}
函数NAVLOAD(){
//在加载页面时运行。
document.getElementById(“主导航”).innerHTML=''+
“家”+
“档案”+
“关于”+
“常见问题”+
“法纳特!”+
''+    
'';
}
功能转到(第页){
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>


导航表显示正确,但当我单击它时,链接不起任何作用然而,当我将NAVLOAD()函数中看到的HTML放在HTML文件中,并且只从文件中导入goTo()方法时,链接就起作用了!这里有什么问题?

您需要在包含NAVLOAD()方法的JS文件中进行以下更正。将引号从双引号(“”)更改为单引号(“”),为此,您还必须添加转义字符(“\”)

函数NAVLOAD(){
//在加载页面时运行。
document.getElementById(“主导航”).innerHTML=''+
“家”+
“档案”+
“关于”+
“常见问题”+
“法纳特!”+
''+    
'';
}

希望有帮助:)

你用Javascript构建导航菜单的理由是什么,为什么要用表格呢?我有多个页面都有相同的导航栏,而且我的学校提供的免费网络主机不提供SSI或PHP。导航菜单会经常改变吗?如果没有,最好是将导航硬编码到每个页面中。此外,您不应该使用表格来构建导航,表格用于表格数据,在当今时代应该很少使用。通常,用于构造导航。也就是说,Javascript的问题是
goTo()
函数超出范围。正在处理我的本地副本。。。您是否使用开发人员工具..在您的终端调试问题?
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>';
}