jQuery イベント取得時にパラメータのデータを渡すサンプル
環境
Google Chrome 105.0.5195.127
Windows 10 Home 64bit
jquery 3.6.1
構文
$('セレクターID名’).on('click’),{変数名:"値"},functionm(){処理コード})
onメソッドmにパラメータにオブジェクトの値を指定して、イベント取得時にデータを渡します。
${e.data.変数名}
イベント取得時にパラメータの値を取得します。
使用例
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(function(){
$('#btnadd').on('click', {city: "tokyo"}, function (e) {
$('#result').text( `${e.data.city}の値を取得した` )
})
});
</script>
</head>
<body>
<h2 id="result"></h2>
<div >
<button id="btnadd" >実行</button>
</div>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script>
<script>
$(function(){
$('#btnadd').on('click', {city: "tokyo"}, function (e) {
$('#result').text( `${e.data.city}の値を取得した` )
})
});
</script>
</head>
<body>
<h2 id="result"></h2>
<div >
<button id="btnadd" >実行</button>
</div>
</body>
</html>
<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.1/jquery.min.js"></script> <script> $(function(){ $('#btnadd').on('click', {city: "tokyo"}, function (e) { $('#result').text( `${e.data.city}の値を取得した` ) }) }); </script> </head> <body> <h2 id="result"></h2> <div > <button id="btnadd" >実行</button> </div> </body> </html>
実行結果
「実行」ボタンを押すと、「tokyoの値を取得した」が表示されます。