Javascript基于星期几隐藏/显示div? [英] Javascript hide/show div based on the day of the week?

查看:113
本文介绍了Javascript基于星期几隐藏/显示div?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个基于星期几更改内容的动态页面。我以为我有解决方案,但我似乎无法使其工作:

I am trying to create an dynamic page that changes content based on the day of the week. I thought I had the solution, but I can't seem to make it work:

<html>
<head>
<script type="text/javascript">
function showhide(id) {
    var d = new Date();
    var s = document.getElementById[d.getDay()];
    s.style.display = (s.style.display == 'block') ? 'none' : 'block';

}
</script>
</head>
<body onload="javascript:showhide[d.getDay()]">
<div id="0" style="display:none;">
     <h3>Sunday</h3>

</div>
<div id="1" style="display:none;">
     <h3>Monday</h3>

</div>
<div id="2" style="display:none">
     <h3>Tuesday</h3>

</div>
<div id="3" style="display:none">
     <h3>Wednesday</h3>

</div>
<div id="4" style="display:none">
     <h3>Thursday</h3>

</div>
<div id="5" style="display:none">
     <h3>Friday</h3>

</div>
<div id="6" style="display:none">
     <h3>Saturday</h3>

</div>
</body>
</html>

我怀疑它是非常简单的东西我想要过度思考它,或者它只是我喜欢的东西尚未掌握。任何指导我正确方向的帮助都将非常感激。

I suspect it's either something really simple and I'm way overthinking it, or it's something that I just haven't grasped yet. Any help pointing me in the right direction would be greatly appreciated.

到目前为止我的资料来源是w3schools,jsfiddle和here(我从另一个人那里借了一段我的代码)发布在这里)。

My sources so far have been w3schools, jsfiddle, and here (I borrowed a snippet of my code from another post here).

提前感谢您的回复。

推荐答案

几乎在那里,将document.getElementById []更改为document.getElementById()&将脚本添加到页面底部(标记下方和''标记之前),您可以删除body onload事件,只需调用以下函数:

Nearly there, change document.getElementById[] to document.getElementById() & add the script to the bottom of the page(below your markup and just before the '' tag) and you can remove the body onload event and just call the function as below:

...
<div id="6" style="display:none">
   <h3>Saturday</h3>

</div>
<script>
  function showhide() {
    var d = new Date();
    var s = document.getElementById(+d.getDay());
    s.style.display = (s.style.display == 'block') ? 'none' : 'block';
  }
  showhide();
</script>
</body>
</html>

参见 http://jsfiddle.net/sjmcpherso/wyoffLw6/

通过调用页面底部的功能(在标记之后)当页面上的所有元素都已加载

By calling the function at the bottom of the page(after your markup) you are effective triggering the function when all the elements on the page have loaded

这篇关于Javascript基于星期几隐藏/显示div?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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