锚标签列表创建
我正在从 MySQL/PHP 查询创建锚标记列表;锚标记调用 JavaScript 函数。
我的“第 22 条军规”是:
href="#"
使页面在每次单击锚标记之一时跳转到顶部(非常烦人),- 删除
href="# "
意味着当锚标记悬停在其上时光标不会改变,该锚标记也不具有锚标记的外观。
我知道有一种方法可以用 JavaScript(可能是 jQuery)来处理这个问题,但我现在不记得如何处理。不过,我确实更喜欢一种不需要我了解 JavaScript 的更简单的 HTML 修复(如果存在的话)。
编辑:
“不需要我了解 JavaScript” ==“不需要对 JavaScript 进行大量更改。”
I am creating a list of anchor tags from a MySQL/PHP query; the anchor tags call a JavaScript function.
The 'catch 22' that I have is:
href="#"
makes the page jump to the top every time one of the anchor tags is clicked (very annoying)- removing
href="#"
means that the cursor does not change as an anchor tag is hovered over nor does that anchor tag have the appearance of an anchor tag.
I know there is a way to handle this with JavaScript (possibly jQuery) but I don't recall how at the moment. However, I really prefer a simpler HTML fix (if one exists) that does not require me to get into JavaScript.
Edit:
"does not require me to get into JavaScript" == "does not require extensive changes in JavaScript."
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
在您的 javascript 函数中,您应该
返回 false
,或者对于 jquery,您可以使用preventDefault()
示例:
或者在您的情况下:
或者将 href 更改为
javascript:void(0)
:理想情况下,您的链接会在没有 javascript 的情况下降级,因此第三个选项通常会被避免。
In your javascript function you should
return false
, or with jquery you can usepreventDefault()
Example:
Or in your case:
Or change the href to
javascript:void(0)
:Ideally, your link degrades without javascript, so the third option will usually be avoided.
为您提供更简单的 HTML 修复:就个人而言,对于普通测试链接,我只使用
href=""
对于指向 javascript 函数的链接,我倾向于使用
href="javascript:;"
。不管怎样,你都会停止页面跳转。A simpler HTML fix for you: Personally speaking, for plain test links I just use
href=""
For links that point to a javascript function I tend to use
href="javascript:;"
. Either way you'll stop the page jumping.在 onclick 之后或在 foo() 函数中返回 false。
do return false after onclick or from within the foo() function.
您需要在点击事件处理程序中的某个位置调用
event.preventDefault();
。在普通的 javascript 中,可以像这样完成:此外,您还可以返回 false:
这也可以在 jQuery 中非常简单地完成:
使用
return false;
的缺点是这也会阻止该事件避免 DOM 冒泡。如果您不关心事件冒泡,可以使用 false,但我个人认为最好使用event.preventDefault();
,除非您特别想停止事件冒泡。You need to call
event.preventDefault();
somewhere in your click event handler. In vanilla javascript, this can be done like so:Additionally, you can also return false:
This can be also done in jQuery pretty simply:
The downside of using
return false;
is that is also prevents the event from bubbling up the DOM. If you don't care about event bubbling it's okay to use false, but personally I feel that it's better to useevent.preventDefault();
unless you specifically want to stop event bubbling as well.只需添加 CSS 并删除
href
似乎就可以了。Just adding the CSS and removing the
href
seems fine.