这是我的html代码
<a href="#" onclick="return clickHandler()">Hit</a>
这是我的 javascript 文件
function clickHandler(evt) {
var thisLink = (evt)?evt.target:Window.event.srcElement;
alert(thisLink.innerHTML);
return false;
}
但是当我点击点击链接时,它会重定向。
这是我的html代码
<a href="#" onclick="return clickHandler()">Hit</a>
这是我的 javascript 文件
function clickHandler(evt) {
var thisLink = (evt)?evt.target:Window.event.srcElement;
alert(thisLink.innerHTML);
return false;
}
但是当我点击点击链接时,它会重定向。
如果您希望阻止默认值,则需要传入事件。
html:
<a href="#" onclick="runFunction(event)">Hit</a>
脚本:
function runFunction (evt) {
evt.preventDefault();
evt.stopPropagation();
}
为了将两个非常正确的答案联系在一起,发生的事情是你已经在你写的地方内联了一个函数onclick="return runFunction();"
如果你看一下,它真正在做的是这样的:
var link = document.getElementById("myLink");
link.onclick = function () { runFunction(); };
看到问题了吗?
我runFunction的调用根本没有传入任何事件对象。...这意味着这var thisLink = (evt) ?将返回 false,这意味着它将尝试在 oldIE 模式下运行。
通过写作onclick="runFunction",这与说:
link.onclick = runFunction;
这意味着当 onclick 事件发生时,会调用 runFunction,并且在 W3C 兼容的浏览器中,它会被发送一个事件对象。
这就是该解决方案有效的原因。
避免这种混淆的最好方法是从 JavaScript 内部处理 JavaScript,并在 HTML 内部处理 HTML,这样您就不必担心字符串如何转换为代码。
现在,为了让所有这些工作,并防止重定向,你想要这样做:
对于 W3C 浏览器(传递事件参数的浏览器):
function runFunction (evt) {
// stops the default-action from happening
// means you need to find another way to fire it, if you want to later
evt.preventDefault();
// stops higher-up elements from hearing about the event
// like if you stop a submit button from "clicking", that doesn't stop the form
// from submitting
evt.stopPropagation();
//the oldIE versions of both of these are
event.cancelBubble = true;
event.returnValue = false;
}
当我将您的代码插入 chrome 时,我在控制台中得到了这个错误: Uncaught TypeError: Cannot read property 'srcElement' of undefined
如果 javascript 在处理过程中爆炸,它根本没有机会返回,因此浏览器倾向于在异常发生后忽略 onclick 处理程序中的内容。
既然它被炸毁了……锚标签的默认行为,就是把你送到href说去的任何地方。
尝试将函数的内容包装在 try/catch 块中,看看如果这种事情困扰你会发生什么。