内联JavaScript的onclick事件

16

这是我的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”时,它会重定向。

3个回答

29

如果您希望阻止默认行为,您需要传递事件(event)。

HTML:

<a href="#" onclick="runFunction(event)">Hit</a>

脚本:

function runFunction (evt) {
    evt.preventDefault();
    evt.stopPropagation();
}

6
注意:在<a>标签中,函数的参数必须精确地为"event",因为它是事件变量的引用。使用其他名称替换,例如runFunction(evt),将无法正常工作。 - Stefan Musarra
如果您不传递参数: onclick=runFunction() 函数runFunction在幕后将变量“event”传递给它。在runFunction内部,typeof event ='object'。 - Stefan Musarra
1
最好在runFunction(event)中传入事件对象,否则变量“event”实际上是window.event。如果有多个快速事件,在执行runFunction时,window.event可能不是触发runFunction的事件对象。 - Stefan Musarra

9
为了将两个非常正确的答案联系起来,发生的情况是您内联了一个函数,其中写有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;    
}

这意味着没有事件传递给函数。谢谢。 - Vicky

0

当我将您的代码插入Chrome时,控制台中出现了以下错误: Uncaught TypeError: Cannot read property 'srcElement' of undefined

如果JavaScript在处理过程中崩溃,它根本没有机会返回,因此浏览器往往会忽略异常后onclick处理程序中的内容。

由于它已经崩溃了...默认行为是将锚点标签发送到href指定的位置。

尝试在函数的内容中包含try/catch块,并查看是否有类似问题困扰您。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接