如何在onclick方法中防止默认事件处理? [英] How to prevent default event handling in an onclick method?

查看:134
本文介绍了如何在onclick方法中防止默认事件处理?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何防止onclick方法中的默认值?我有一个方法,我也传递自定义值

How to prevent default in an onclick method? I have a method in which I am also passing a custom value

<a href="#" onclick="callmymethod(24)">Call</a>





function callmymethod(myVal){
    //doing custom things with myVal
    //here I want to prevent default
}


推荐答案

让你的回调返回 false 并将其传递给 onclick handler:

Let your callback return false and pass that on to the onclick handler:

<a href="#" onclick="return callmymethod(24)">Call</a>

function callmymethod(myVal){
    //doing custom things with myVal
    //here I want to prevent default
    return false;
}






创建但是,您应该避免使用内联Javascript(即:直接在元素标记内的代码)并通过包含的Javascript源文件修改元素的行为(它被称为可维护的代码不引人注目的Javascript )。


To create maintainable code, however, you should abstain from using "inline Javascript" (i.e.: code that's directly within an element's tag) and modify an element's behavior via an included Javascript source file (it's called unobtrusive Javascript).

加价:

<a href="#" id="myAnchor">Call</a>

代码(单独文件):

// Code example using Prototype JS API
$('myAnchor').observe('click', function(event) {
    Event.stop(event); // suppress default click behavior, cancel the event
    /* your onclick code goes here */
});

这篇关于如何在onclick方法中防止默认事件处理?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆