如果我有这个元素:
<a href="www.mysite.com" onClick="javascript.function();">Item</a>
我该如何让 href
和 onClick
都起作用,最好让 onClick
先运行?
如果我有这个元素:
<a href="www.mysite.com" onClick="javascript.function();">Item</a>
我该如何让 href
和 onClick
都起作用,最好让 onClick
先运行?
你已经拥有所需内容,只需要进行微小的语法更改:
<a href="www.mysite.com" onclick="return theFunction();">Item</a>
<script type="text/javascript">
function theFunction () {
// return true or false, depending on whether you want to allow the `href` property to follow through or not
}
</script>
< p > < code ><a>标签的onclick
和href
属性的默认行为是首先执行onclick
,然后只要onclick
没有返回false
,就会跟随href
进行页面跳转,除非事件被取消(或者事件未被阻止)。href="#"
之前,它对我不起作用。 - yegor256click
事件并转到网站。
$("#myHref").on('click', function() {
alert("inside onclick");
window.location = "http://www.google.com";
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" id="myHref">Click me</a>
<a href="www.mysite.com" onclick="make(event)">Item</a>
<script>
function make(e) {
// ... your function code
// e.preventDefault(); // use this to NOT go to href site
}
</script>
<a href="http://example.com" >Item</a>
,在Chrome中,我看到一些消息要求允许页面运行此链接(在Chrome URL栏末尾的警报)。在Safari中,控制台中显示警告:[blocked] https://fiddle.jshell.net/_display/ 的页面未被允许从http://example.com/ 显示不安全的内容 - 所以可能这是某种安全问题(只在fiddle上?) - Kamil Kiełczewski无需使用jQuery。
这个例子使用纯浏览器Javascript。默认情况下,似乎点击处理程序将在导航之前执行,因此如果您希望可以取消导航并执行自己的操作。
<a id="myButton" href="http://google.com">Click me!</a>
<script>
window.addEventListener("load", () => {
document.querySelector("#myButton").addEventListener("click", e => {
alert("Clicked!");
// Can also cancel the event and manually navigate
// e.preventDefault();
// window.location = e.target.href;
});
});
</script>
<button>
代替超链接。通常情况下,只有在导航到实际URL时才应该使用超链接。被接受的答案对我没用。然而,防止 a href
的默认行为,然后“手动”跟随链接是有效的。
代码示例如下:
<a href="https://example.com" onClick="myFunction(event)">Link</a>
<script>
function myFunction(event) {
event.preventDefault();
// do your thing here
window.location.href = event.currentTarget.href;
}
</script>
使用ng-click
代替onclick
。就是这么简单:
<a href="www.mysite.com" ng-click="return theFunction();">Item</a>
<script type="text/javascript">
function theFunction () {
// return true or false, depending on whether you want to allow
// the`href` property to follow through or not
}
</script>