HTML 锚链接-href 和 onclick 都有吗?

我想编写一个锚标记,它执行一些 JavaScript,然后继续前进到 href带它去的地方。调用一个执行我的 JavaScript 并将 window.locationtop.location设置为 href位置的函数对我来说不起作用。

因此,假设我在页面上有一个 id 为“ Foo”的元素,我想创建一个类似于下面这样的锚:

<a href="#Foo" onclick="runMyFunction(); return false;">Do it!</a>

当单击这个命令时,我想执行 runMyfunction,然后将页面跳转到 #Foo(不会导致重新加载——使用 top.location会导致重新加载页面)。

建议? 我很乐意使用 jQuery,如果它可以帮助这里..。

319269 次浏览

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 - 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.

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.

<a href="#Foo" onclick="return runMyFunction();">Do it!</a>

and

function runMyFunction() {
//code
return true;
}

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.

When doing a clean HTML Structure, you can do this.

const element = document.getElementById('link_1')
element.onClick = function (e) {
e.preventDefault()
window.open('_top', element.getAttribute('href'))
}

Using jQuery

$('a#link_1').click(function (e) {
e.preventDefault()
const a = e.target
window.open('_top', a.getAttribute('href'))
})