ここで本当に基本的なもの。クリック関数に名前を付けて、いくつかのパラメーターを割り当てたいと思います。目標は、ユーザーがさまざまなデータを削除できるようにするなど、一般的なタスクに対して汎用関数を 1 つだけ記述できるように、コードを再利用できるようにすることです。
これが私の言いたいことを示すjsfiddleです。
そして、これがそのコードです:
HTML:
<button>delete this</button>
<div data-id="3" class="delete">something bad</div>
<div data-id="4" class="delete">something else bad</div>
そしてJS:
// this function would be loaded on my site's template and therefore would be available across my entire site.
function deleteThis(data_id){
$('button').on('click', 'button', function(){
$('div[data-id="'+data_id+'"]').hide();
});
}
var clicked_id=3;
function deleteThis(clicked_id);
// this function would be called on the various pages where users can delete things and this variable, clicked_id, would be assigned=3 by the user's action on that page.
このボタン クリック イベントに名前を付けるにはどうすればよいですか?
更新ありがとう!またはボタンの親要素である$('button')
必要があります。$(document.body)
その単純な変更を加えれば機能します。Michael Buen が以下で提案しているように、それを行うこともできます。