HTML 锚链接 - href 和 onclick 两者?
我想编写一个锚标记,它执行一些 JavaScript,然后继续转到 href
所指向的位置。调用执行 JavaScript 的函数,然后将 window.location
或 top.location
设置为 href
位置对我来说不起作用。
所以,假设页面上有一个 id 为“Foo”的元素。我想创作一个类似于以下内容的锚点:
<a href="#Foo" onclick="runMyFunction(); return false;">Do it!</a>
单击此锚点时,我想执行 runMyFunction,然后将页面跳转到 #Foo
(不会导致重新加载 - 使用 top.location
会导致它重新加载页面)。
建议?如果 jQuery 能在这里提供帮助,我很高兴使用它......
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.
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>
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).
Suggestions? I am happy to use jQuery if it can help here...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
只需
返回 true
即可?onClick
代码的返回值决定了链接的固有点击操作是否被处理 - 返回false
意味着它没有被处理,但如果您返回 < code>true 那么浏览器将在函数返回后继续处理它并转到正确的锚点。Just
return true
instead?The return value from the
onClick
code is what determines whether the link's inherent clicked action is processed or not - returningfalse
means that it isn't processed, but if you returntrue
then the browser will proceed to process it after your function returns and go to the proper anchor.这样
,您将执行 youf 函数,并且您将点击该链接,并且您将在函数成功运行后准确点击该链接。
and
This way you will have youf function executed AND you will follow the link AND you will follow the link exactly after your function was successfully run.
如果链接仅在函数运行成功时才更改位置,则执行
onclick="return runMyFunction();"
并在函数中返回 true 或 false。如果您只想运行该函数,然后让锚标记完成其工作,只需删除
return false
语句即可。附带说明一下,您可能应该使用事件处理程序,因为内联 JS 并不是一种非常理想的处理方式。
If the link should only change the location if the function run is successful, then do
onclick="return runMyFunction();"
and in the function you would return true or false.If you just want to run the function, and then let the anchor tag do its job, simply remove the
return false
statement.As a side note, you should probably use an event handler instead, as inline JS isn't a very optimal way of doing things.
当做一个干净的 HTML 结构时,你可以这样做。
使用 jQuery
When doing a clean HTML Structure, you can do this.
Using jQuery