javascript - style.display ="block"仅针对默认div 在页面打开时不起作用

标签 javascript jquery html css display

所以这是我的想法:我正在为我工​​作室的网站编写程序,但只在一个页面中。当你点击一个按钮继续......例如,“原因”页面时,你不是重定向而是页面内容改变!基本上代码非常简单,像这样:

function soloprenota() {
  document.getElementById("article1").style.display = "block";
  document.getElementById("article2").style.display = "none";
  document.getElementById("article3").style.display = "none";
}

function soloilnostrosuono() {
  document.getElementById("article1").style.display = "none";
  document.getElementById("article2").style.display = "block";
  document.getElementById("article3").style.display = "none";
}

function soloreasonwhy() {
  document.getElementById("article1").style.display = "none";
  document.getElementById("article2").style.display = "none";
  document.getElementById("article3").style.display = "block";
}

当您单击导航栏上的相关按钮时,将调用函数,并且一切正常。问题开始于我意识到,首先,当页面加载时,用户没有给出预期的操作,因此似乎没有办法告诉 JavaScript 将其中一个 div 设置为“默认值”。

我试过很多方法,最合乎逻辑的可能是这个:

if (jQuery.isDefined(soloprenota) || jQuery.isDefined(soloilnostrosuono) jQuery.isDefined(soloreasonwhy)) {
  var examplevar = "examplevaluerlyididntknowwhattomakeitdoesincaseofthis";
} else {
  document.getElementById("article1").style.display = "block";
  document.getElementById("article2").style.display = "none";
  document.getElementById("article3").style.display = "none";
}

但永远不会改变,在第一个加载页面仍然显示所有的 div。 我该怎么做才能解决这个问题? :/

最佳答案

只需添加 soloprenota();作为你的 <script> 的最后一行.这将使 soloprenota 成为默认设置。

检查下面的例子。

function soloprenota() {
  document.getElementById("article1").style.display = "block";
  document.getElementById("article2").style.display = "none";
  document.getElementById("article3").style.display = "none";
}

function soloilnostrosuono() {
  document.getElementById("article1").style.display = "none";
  document.getElementById("article2").style.display = "block";
  document.getElementById("article3").style.display = "none";
}

function soloreasonwhy() {
  document.getElementById("article1").style.display = "none";
  document.getElementById("article2").style.display = "none";
  document.getElementById("article3").style.display = "block";
}

soloprenota();
<nav>
  <ul>
    <li onclick="soloprenota()">soloprenota</li>
    <li onclick="soloilnostrosuono()">soloilnostrosuono</li>
    <li onclick="soloreasonwhy()">soloprenota</li>
    </ul>
  </nav>
<div id="article1">article 1</div>
<div id="article2">article 2</div>
<div id="article3">article 3</div>

关于javascript - style.display ="block"仅针对默认div 在页面打开时不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36592141/

相关文章:

javascript - JavaScript 数组中需要迭代器吗?

javascript - 在三星智能电视应用程序中实现内容滚动条

jquery - IE输入选择框

javascript - 从 jquery 中的 xml 数组中删除重复的项目

jquery - 一个子菜单一次打开一个并单击关闭

javascript - 基本 JavaScript : How can I link my HTML and Javascript on a Highcharts example?

javascript - 为什么这个 jQuery 返回 true?

html - 如何在较小的屏幕上将 2 行和 2 列移动到 1 行,但按顺序更正列

java - 将 HTML 与 Swing 结合使用的可行库

javascript - 从内容上方的重叠区域中删除三 Angular 形的阴影?