HTML 锚链接 - href 和 onclick 两者? [英] HTML anchor link - href and onclick both?
问题描述
我想编写一个执行一些 JavaScript 的锚标记,然后继续前往 href
使用它的任何地方.调用执行我的 JavaScript 然后将 window.location
或 top.location
设置为 href
位置的函数对我不起作用.
I want to author an anchor tag that executes some JavaScript and then proceeds to go wherever the href
was taking it. Invoking a function that executes my JavaScript and then sets window.location
or top.location
to the href
location doesn't work for me.
所以,假设我在页面上有一个 ID 为Foo"的元素.我想创作一个类似于以下内容的锚点:
So, imagine I have an element with id "Foo" on the page. I want to author an anchor similar to:
<a href="#Foo" onclick="runMyFunction(); return false;">Do it!</a>
当它被点击时,我想执行 runMyFunction 然后将页面跳转到 #Foo
(不会导致重新加载 - 使用 top.location
会导致它重新加载页面).
When this is clicked, I want to execute runMyFunction and then jump the page to #Foo
(not cause a reload - using top.location
would cause it to reload the page).
建议?如果 jQuery 对这里有帮助,我很乐意使用它...
Suggestions? I am happy to use jQuery if it can help here...
推荐答案
只用 return true
代替?
onClick
代码的返回值决定了链接的固有点击操作是否被处理 - 返回 false
意味着它没有被处理,但如果您返回 true
然后浏览器将在您的函数返回后继续处理它并转到正确的锚点.
The return value from the onClick
code is what determines whether the link's inherent clicked action is processed or not - returning false
means that it isn't processed, but if you return true
then the browser will proceed to process it after your function returns and go to the proper anchor.
这篇关于HTML 锚链接 - href 和 onclick 两者?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!