javascript - 简化 JS,因此不需要在脚本中硬编码哈希

标签 javascript jquery hash

我正在尝试找到一种方法来简化此脚本,以便它不需要硬编码的哈希名称。因此,如果您添加一个带有哈希 mytest 的新链接和一个 ID 为 mytest 的 div,它将起作用,而无需访问脚本并将 mytest 添加到脚本中。希望我能清楚地表达我的问题。

非常感谢您帮助解决这个问题。

            jQuery(function($) {
              $('#menu-bottomnav li a').click(function(e) {
                e.preventDefault();
                animateSlider(this.hash);
              });

              function animateSlider(hash) {
                if (!$('#popups div.open').length) {
                  if (hash == '#bio') {
                    openPopup(hash);
                  }
                  if (hash == '#resume') {
                    openPopup(hash);
                  }
                } else {
                  if (hash == '#bio') {
                    openAndClose(hash)
                  }
                  if (hash == '#resume') {
                    openAndClose(hash)
                  }
                }
              }


              function openPopup(hash) {
                $(hash).slideToggle().addClass('open');
              }


              function openAndClose(hash) {
                if ($(hash).hasClass('open')) {
                  $($(hash)).slideToggle().removeClass('open');
                } else {
                  $('#popups div.open').slideToggle().removeClass('open');
                  $(hash).slideToggle().addClass('open');
                }
              }
            });

这里有一个工作示例 https://jsfiddle.net/a4y7z2fm/

最佳答案

像这样怎么样:

jQuery(function($) {
  $('#menu-bottomnav li a').click(function(e) {
    e.preventDefault();
    animateSlider(this.hash);
  });

  function animateSlider(hash) {
    $('.open').slideToggle().removeClass('open');
    $(hash).slideToggle().addClass('open');
  }
});

关于javascript - 简化 JS,因此不需要在脚本中硬编码哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42744686/

相关文章:

javascript - ES6 求对象数组的最大数量

javascript - jQuery 的when.apply 和包装的异步函数

jquery - 图像无响应或无法调整为最大宽度值

c - 哈希函数问题 - 添加功能

mysql - MySQL 中的分区表

javascript - 如何不在 Phaser 3 中渲染对象

javascript - 在 HTML 文本/链接上实现 "Learn More"气球

php - 在 jquery 中向表中添加项目

javascript - 在 Html 应用程序中,使用 javascript,如何获取图像在屏幕上的位置并将其放入文本文档中?

python - 为字典实现自定义键,以便同一类的 2 个实例匹配