if 语句太多?在页面上显示 div 取决于哈希参数

Too many if statements? Display div on page depends on hash param

提问人:Phillyday 提问时间:10/4/2023 最后编辑:Victory OsiobePhillyday 更新时间:10/5/2023 访问量:60

问:

我有多个页面(大约 250 个),每个页面的末尾都有一个按钮,可以将用户发送到由下载链接组成的同一页面。因此,单击这些按钮后,用户将被带到这个有 250 个隐藏按钮的页面,但正确的按钮只会在 url 具有某个哈希参数时显示。

我想出了下面的代码。但是,因为我有 250 页,这意味着页面上会变成 250 个 if 语句和 250 个隐藏按钮。这太多了吗......有没有更好的方法可以做到这一点?

<!-- Page 1: -->

<a href="download-page/#download1">Download PDF</a>

<!-- Page 2: -->

<a href="download-page/#download2">Download PDF</a>

<!-- Page 3: -->
<a href="download-page/#download3">Download PDF</a>

下载页面(download-page):

<style>

    #hidden_download1 { display none; }
    #hidden_download2 { display none; }
    #hidden_download3 { display none; }

</style>

<script>
    $(function() {
    if (location.hash === "#download1") {
    $("#hidden_download1").fadeIn(700);
    }
    $(function() {
    if (location.hash === "#download2") {
    $("#hidden_download2").fadeIn(700);
    }
    $(function() {
    if (location.hash === "#download3") {
    $("#hidden_download3").fadeIn(700);
    }
});
<script>

<div id="hidden_download1"><a class="download-btn" href="https://drive.google.com/file/1">Download File</a></div>

<div id="hidden_download2"><a class="download-btn" href="https://drive.google.com/file/2">Download File</a></div>

<div id="hidden_download3"><a class="download-btn" href="https://drive.google.com/file/3">Download File</a></div>

有什么建议吗?这是太乱了还是没关系?有没有更好的方法可以做到这一点?我有点生疏,所以请放轻松!

非常感谢!

JavaScript 函数 if 语句 哈希 查询字符串

评论

0赞 Steven B. 10/4/2023
是否可以根据 URL 中的哈希值构造 hrefs?例如,您能否拥有 1 个锚点并根据哈希值设置 href?
0赞 Phillyday 10/4/2023
这是个好主意,可以清理页面上的 250 个不同按钮。但它仍然由 250 个 if 语句组成。有没有办法清理那部分?
0赞 deceze 10/4/2023
请注意,所有这些 if 语句之间的唯一区别是 中的数字。并且这个确切的数字出现在哈希值中。你可以说,这个数字是一个变量......!可以从哈希中读取并放入需要它的地方......!download1

答:

0赞 rachitiitr 10/5/2023 #1

您需要定义从中获取 DOM 的规则,然后下面的代码就可以正常工作了。idlocation.hash

<script>
    $(function() {
       const id = getIdFromHash();
       $(id).fadeIn(700);
    }
});
<script>

您现在可以决定如何编写 HTML 和函数。我会建议这样的事情——getIdFromHash

function getIdFromHash() {
   const hash = location.hash;
   const id = hash; // keep id and hash values same
   return id;
}

但是,如果您出于某种原因不想保持不变,那么对于您最初的问题,这将起作用hashid

function getIdFromHash() {
   const hash = location.hash;
   const id = "#hidden_" + hash.substring(1);
   return id;
}