两次使用相似/相同的Javascript

时间:2019-07-02 04:36:25

标签: javascript jquery

第一次发布时,我不会把我的Javascript知识称为基本知识,所以请原谅我的无知。

上周,我在这里找到了一段代码(如第一个代码示例所示),并且我试图获得一个经过调整的版本,以便同时使用。

两个都一起加载到页脚中,如下所示,但是第一个起作用,随后的一个不运行

我已经在页脚中交换了他们的顺序,并确认只有第一个调用才能正常运行,我认为这只是冲突,但是我不知道是什么。

// First function call

$(function() {
  var items = $('#v-nav>ul>li').each(function() {
    $(this).click(function() {
      //remove previous class and add it to clicked tab
      items.removeClass('current');
      $(this).addClass('current');

      //hide all content divs and show current one
      $('#v-nav>div.tab-content').hide().eq(items.index($(this))).show();

      window.location.hash = $(this).attr('tab');
    });
  });

  if (location.hash) {
    showTab(location.hash);
  } else {
    showTab("tab1");
  }

  function showTab(tab) {
    $("#v-nav ul li:[tab*=" + tab + "]").click();
  }

  // Bind the event hashchange, using jquery-hashchange-plugin
  $(window).hashchange(function() {
    showTab(location.hash.replace("#", ""));
  })

  // Trigger the event hashchange on page load, using jquery-hashchange-plugin
  $(window).hashchange();
});

// Second function call

$(function() {
  var items = $('#h-nav>ul>li').each(function() {
    $(this).click(function() {
      //remove previous class and add it to clicked tab
      items.removeClass('current');
      $(this).addClass('current');

      //hide all content divs and show current one
      $('#h-nav>div.tab-content').hide().eq(items.index($(this))).show();

      window.location.hash = $(this).attr('tab');
    });
  });

  if (location.hash) {
    showTab(location.hash);
  } else {
    showTab("tab1");
  }

  function showTab(tab) {
    $("#h-nav ul li:[tab*=" + tab + "]").click();
  }

  // Bind the event hashchange, using jquery-hashchange-plugin
  $(window).hashchange(function() {
    showTab(location.hash.replace("#", ""));
  })

  // Trigger the event hashchange on page load, using jquery-hashchange-plugin
  $(window).hashchange();
});

https://codepen.io/adouglas1880/pen/RzMqBV

0 个答案:

没有答案