内联 javascript onclick 事件

问题描述 投票:0回答:3

这是我的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;
}

但是当我点击点击链接时,它会重定向。

javascript
3个回答
29
投票

如果你想阻止Default,你需要传入该事件。

html:

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

脚本:

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

9
投票

为了将两个非常正确的答案联系在一起,你已经内联了一个你编写的函数

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;    
}

0
投票

当我将你的代码插入 Chrome 时,我在控制台中收到以下错误: 未捕获的类型错误:无法读取未定义的属性“srcElement”

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

自从它被轰炸后...锚标记的默认行为,即将您发送到 href 所说的任何地方。

尝试将函数的内容包装在 try/catch 块中,看看如果这种事情困扰你会出现什么情况。

© www.soinside.com 2019 - 2024. All rights reserved.