这是我的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;
}
但是当我点击“Hit Link”时,它会重定向。
这是我的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;
}
但是当我点击“Hit Link”时,它会重定向。
如果您希望阻止默认行为,您需要传递事件(event)。
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,这意味着它将尝试在旧版IE模式下运行。
通过编写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块,并查看是否有类似问题困扰您。