内联javascript onclick事件

Vic*_*cky 11 javascript

这是我的HTML代码

<a href="#" onclick="return clickHandler()">Hit</a>
Run Code Online (Sandbox Code Playgroud)

这是我的javascript文件

function clickHandler(evt) {
    var thisLink = (evt)?evt.target:Window.event.srcElement;
    alert(thisLink.innerHTML);
    return false;
}
Run Code Online (Sandbox Code Playgroud)

但是当我点击命中链接时,它会重定向.

Tro*_*zie 14

如果你想阻止默认,你需要传递这个事件.

HTML:

<a href="#" onclick="runFunction(event)">Hit</a>
Run Code Online (Sandbox Code Playgroud)

脚本:

function runFunction (evt) {
    evt.preventDefault();
    evt.stopPropagation();
}
Run Code Online (Sandbox Code Playgroud)

  • 注意:在<a>标记中,函数的参数必须是"event",因为它是对事件变量的引用.替换其他名称,如runFunction(evt)将无法正常工作. (4认同)

Nor*_*ard 9

为了将两个非常正确的答案结合在一起,发生的事情是你已经编写了一个你写过的函数 onclick="return runFunction();"

如果你看一下,它真正做的是这样的:

var link = document.getElementById("myLink");

link.onclick = function () { runFunction(); };
Run Code Online (Sandbox Code Playgroud)

看到问题?

runFunction在没有传入任何事件对象的情况下调用我....这意味着它将var thisLink = (evt) ?返回false,这意味着它将尝试在oldIE模式下运行.

通过写作onclick="runFunction",这与说:

link.onclick = runFunction;
Run Code Online (Sandbox Code Playgroud)

这意味着当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;    
}
Run Code Online (Sandbox Code Playgroud)