javascript - 脚本部分无法在页面加载时隐藏

标签 javascript jquery

我和我的 friend 们正在努力解决这个问题。问题是类 id 调用 z 无法在页面加载时完全隐藏。它显示了 z 的一部分,但我们

期望 z 中的所有内容(包括 z 本身)在页面加载时隐藏,我们想按下按钮来查看整个 z 类,但我们在这样做时遇到问题,那么我们如何在看起来像这样的地方做到这一点.

GIF Screenshot 1

我们不希望它看起来像现在这样。

GIF Screenshot 2

index.php

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
  $(document).ready(function() {
  var z = $('.z');
  var x = $('#x');
  
  var XHR = function() { output = "";
  $.getJSON("x.json", function(data) {
    $.each(data.shop, function(index, element) {
        for (var j in element) {
          output += element[j] + '<br>';
        }
      });
      x.html(output);
   });
};
  $("button").click(function(){ XHR(); });
z.show();
});
  </script>
  <style>
  h1 {
  color: gold;
}

#x {
  color: white;
  text-align: center;
}
.z {
  background-color: red;
  width: 250px;
  margin: auto;
  padding-bottom: 5px;
display: none;
}
  </style>
</head>
<body>
<div class="z">
<h1>Details </h1>
<h2 id="x"></h2>
</div>
<button>Click</button>
</body>
</html>

x.json

{
        "shop": [{
                "item": "Ps3",
                "cost": "$150"
            },
            {
                "item": "xbox 360",
                "cost": "$140"
            },
            {
                "event": "Black Friday",
                "date": "4-25-2018"
            },
            {
                "special_guest": "John Doe",
                "time": "4:30 pm"
            }
        ]
    }

最佳答案

在当前代码中,加载页面时显示 Z 类,如果我没有误解,请尝试更改程序:

$("button").click(function(){ XHR();});
z.show();

就这样

$("button").click(function(){ 
  XHR();
  z.show();
});

或者如果你想在加载后看到 Z 类:

  $(document).ready(function() {
  var z = $('.z');
  var x = $('#x');

  var XHR = function() { output = "";
  $.getJSON("x.json", function(data) {
    $.each(data.shop, function(index, element) {
        for (var j in element) {
          output += element[j] + '<br>';
        }
      });
      x.html(output);
      z.show(); // Show Z div!
   });
};
  $("button").click(function(){ XHR(); });
});

关于javascript - 脚本部分无法在页面加载时隐藏,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46253043/

相关文章:

php - 需要从数据库中获取值并使用 jQuery 填充下拉列表

javascript - 如何正确使用数组和循环

javascript - 使用 jquery 可排序和 css 变换/过渡

javascript - 在 asp.net c# 中使用 jquery 进行 ckeditor 验证

javascript - 谷歌电子表格循环器

javascript - 在 Vuejs 项目中使用 jsPDF 和 html2canvas(没有 webpack)

javascript - 我正在尝试将文本拆分为段落,它是使用 javascript 以逗号而不是新行或段落进行拆分

javascript - 使用 jQuery 将数据放入动态内容

javascript - jQuery 中的随机颜色

jquery - 绝对位置的表单验证器给出错误但发布表单