1. ホーム
  2. javascript

[解決済み] onclickメソッドでデフォルトのイベント処理を行わないようにするには?

2023-01-16 04:38:25

質問

onclickメソッドでデフォルトを防ぐには?私はまた、私はカスタム値を渡しているメソッドを持っています。

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

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

どのように解決するのですか?

コールバックが以下を返すようにします。 false を返し、それを onclick ハンドラに渡します。

<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 ソースファイル (これは 控えめなジャバスクリプト ).

マークアップです。

<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 */
});