LoginSignup
33
31

More than 5 years have passed since last update.

#jQuery イベント実行時に任意の引数を渡す

Posted at

trigger()を使う

コード

受け手側

jQuery
$(document).on('click', '#button', function(event, p1, p2){

});
  • 第一引数にはイベントオブジェクト(event)が渡ってくるので、第二引数以降(p1, p2)を用意。
  • 他の方法としては、arguments で取り出すなど。

呼び出し側

jQuery
$('#button').trigger('click');
$('#button').trigger('click', ['パラメータ1']);
$('#button').trigger('click', ['パラメータ1', 'パラメータ2']);
  • trigger() の第二引数に配列で渡す。

Example

html
<!DOCTYPE html>
<html lang="ja">
<head>
<meta charset="UTF-8"/>
<title>Example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>

<script>
$(function(){
    $(document).on('click', '#button', function(event, p1, p2){
        console.log(arguments);
        console.log(p1);
        console.log(p2);
    });
    $(document).on('click', '#button1', function(){
        $('#button').trigger('click', [$(this).text()]);
    });
    $(document).on('click', '#button2', function(){
        $('#button').trigger('click', [$(this).text(), 'ほげほげ']);
    });
});
</script>

</head>
<body>

<button id="button">BUTTON</button><br/><br/>
<button id="button1">ボタン1</button><br/><br/>
<button id="button2">ボタン2</button><br/><br/>

</body>
</html>

Result

Windows 7 64 bit Google Chrome バージョン 46.0.2490.86 m で実行。

このボタンをクリック arguments p1 p2
BUTTON [m.Event] undefined undefined
ボタン1 [m.Event, "ボタン1"] ボタン1 undefined
ボタン2 [m.Event, "ボタン2", "ほげほげ"] ボタン2 ほげほげ
33
31
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
33
31