需要帮助在javascript中的表之间切换 [英] need help switching between tables in javascript

查看:40
本文介绍了需要帮助在javascript中的表之间切换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让两个按钮使用javascript在2个表之间切换,但是每当我进行测试时,两个表都会出现,而不仅仅是一个表

I'm trying to get two buttons to switch between 2 tables with javascript, but whenever i test, both of the tables appear instead of just one

var table1 = document.getElementById("table1");
var table2 = document.getElementById("table2");

var btnTab1 = document.getElementById("showTable1");
var btnTab2 = document.getElementById("showTable2");

btnTab1.onclick = function() {
  table1.style.display = "table";
  table2.style.display = "none";
}

btnTab2.onclick = function() {
  table1.style.display = "none";
  table2.style.display = "table";
}

<table id=table1>
<table id=table2>

<input type="button" id="showTable1" value="Table 1">
<input type="button" id="showTable2" value="Table 2">

我希望一次显示1张表,并在它们之间进行切换,但是相反,它们都同时显示,并且按钮什么也没做

I expect 1 table to be showing at a time and the button to switch between them, but instead they both show at the same time and the buttons dont do anything

推荐答案

如果您的代码块位于标头中,请尝试将其向下移动到闭包主体标签之前.我只是以两种方式运行它,它在标题中不起作用,而在正文中却起作用.

If your code block is in the header, try moving it down to just before the closing body tag. I just ran it both ways, and it doesn't work in the header, does work in body.

原因:脚本已加载到html之前的标头中,因此getelementbyid调用返回null.通过将脚本放置在html后面,div会填充id,然后脚本会正确加载它.

The reason: the script is loaded in the header before the html, so the getelementbyid call returns null. By placing the script after the html, the div populates the id and the script loads it properly.

如果您在Chrome中加载文件并打开Javascript控制台,则会看到类似于以下内容的错误消息:

If you load your file in Chrome and turn on the Javascript console, you would have seen an error message similar to the following:

(index):12 Uncaught TypeError: Cannot set property 'onclick' of null
at (index):12

这篇关于需要帮助在javascript中的表之间切换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆