e.preventDefault() 以防止锚点跳转到 ID 不适用于匿名函数

e.preventDefault() to prevent anchor jumping to the ID not working on anonymous function

我有以下 jQuery/JS 在单击元素时触发一些东西:

$(tabs).click(function(e) {
    tabs.removeClass('active');
    $(this).addClass('active');

    $(tabIDs).removeClass('js_tab_area_show');
    $($(this).attr('href')).addClass('js_tab_area_show');

    e.preventDefault();
    alert('worked');
});

tabs 这里已经在函数之前初始化了,并且选择了我想要定位的元素。上面所有的东西都已经在工作了。但是,我现在想要禁用锚元素(即 tabs 在这种情况下)滚动到具有包含在我的锚的 href 属性中的 ID 的元素。我试着环顾四周,许多人建议 preventDefault() 以防止滚动。但是,它对我不起作用。我主要看到的唯一区别是它们有一个命名函数,专门用于处理从点击函数内部调用的点击事件。另一方面,我的做了上述。 alert('worked') 确实触发了,表示代码执行到最后。我这里做错了什么?

href修改

不要让您的 JavaScript/jQuery 或 CSS 过于复杂,而是执行以下操作。

<a href="#/">I DON't JUMP</a>

☝ 只需添加正斜杠:/

如果您有大量 link 并且没有可用的服务器端实用程序,请参阅 Demo 2。它有一个简单的 JavaScript link 收集器。


演示 1

h1,
h2 {
  text-align: center
}

h2 {
  font-size: 64px
}

a {
  display: inline-block;
  height: 30px;
  font-size: 24px;
  width: 40%;
  margin: 400px 0;
}

a:first-of-type {
  color: red;
  text-align: right;
}

a:last-of-type {
  color: blue;
  text-align: left;
}
<main>
  <h1>Scroll Down</h1>
  <h2>⇩</h2>
  <a href="#">Click me.<br>I JUMP.</a>
  <a href="#/">Click me.<br>I DO NOT JUMP.</a>
</main>


演示 2

Array.from(document.querySelectorAll('a')).forEach(lnx => {
  if (lnx.getAttribute('href') === '#') lnx.setAttribute('href', "#/");
});
h1,
h2 {
  text-align: center
}

h2 {
  font-size: 64px
}

main {
  margin: 400px auto;
}

a:nth-of-type(odd) {
  background: #000;
  color: #fff;
}

a:nth-of-type(even) {
  color: #000;
}
<h1>Scroll Down</h1>
<h2>⇩</h2>
<main>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
  <a href='#'>WE DON'T JUMP</a>
</main>