Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

trigger()を使う

http://semooh.jp/jquery/api/events/trigger/type,+%5Bdata%5D/

コード

受け手側

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 ほげほげ
nfnoface
主に自分のメモとして利用しています。 2016年も引き続きCakePHP・PostgreSQLの話題が中心になりそうです。 個人的にはCrystal-langに興味あり。 気分や時々によりメモ内容は変わります。 書き残しておけば繰り返し調べる労力が減るかもしれないと思い立ち2015年から利用しています。
https://teratail.com/users/nfnoface
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
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  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
ユーザーは見つかりませんでした