Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
32
Help us understand the problem. What are the problem?

More than 5 years have passed since last update.

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

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 ほげほげ
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
32
Help us understand the problem. What are the problem?