//this would bind a handler that would execute anytime the ul is clicked
$('.js-click').on('click', function(e) { });
あなたは2つの質問をしています。ハンドラをバインドする方法、データ属性にアクセスする方法
はあなたがあなたのjs-click
クラスにハンドラをバインドに近いですハンドラをバインドしますが、フィルタを追加することによって、よりきめ細かを得ることができます。
Refer to the jQuery docs for more info.
$('.js-click').on([event], [filter], [handler]);
//Bind a handler to js-click, but only execute for <a> elements
$('.js-click').on('click', 'a', function(e) { });
属性にdata-
接頭辞を含めることにより、そのデータ属性
へのアクセス
は、あなたはそれが準備ができたときに自動的に値をキャッシュするためのjQueryを言っています。
<a href="" data-attr="hello">Hello</a>
Refer to jQuery data docs for more info
は、あなただけのこのケースで
attr
だろうキーを使用する必要があり、データにアクセスするには
$('a').data('attr', 'hello');
に相当します。 はに直接アクセスできますが、どちらか一方(好ましくは.data
)を使用することに注意してください。
あなたのマークアップで... <a href="" data-attr="hello">Hello</a>
$('.js-click').on('click', 'a', function(e) {
var $this = $(this);
$this.data('attr', 'I changed');
//what will the value be? It's going to be 'Hello', because we're accessing the attribute in the DOM
alert($this.attr('data-attr'));
//what will the value be? It's going to be 'I changed', because we're accessing the data cache
alert($this.data('attr'));
});
は、それらを一緒に入れて、あなたはこれを行うことができます。
$('.js-click').on('click', 'a', function(e) {
var data = $(this).data('attr');
//quick sanity check to make sure the attribute exists
if(typeof data !== 'undefined') {
//do stuff
}
});
私はそれが他の答えは罰金になり、アンカータグであることを確認するために、ターゲットをチェックすることをお勧め
は –
そうだね、ありがとう – Maak