jqueryオブジェクトにプロパティを追加したい。jquery のコンテキストにプロパティを追加しようとしています。jquery オブジェクト console.log($(this)) をコンソール化します。これはオブジェクトのように見えます。しかし、コードを修正しようとすると、フィドルが機能しません
$('ul').click(function(){
$(this).myul={'date':'28 april'}
console.log($(this))
})
jqueryオブジェクトにプロパティを追加したい。jquery のコンテキストにプロパティを追加しようとしています。jquery オブジェクト console.log($(this)) をコンソール化します。これはオブジェクトのように見えます。しかし、コードを修正しようとすると、フィドルが機能しません
$('ul').click(function(){
$(this).myul={'date':'28 april'}
console.log($(this))
})
HTML の data- 属性にデータを追加できるため、次のオプションを保存できます。
$(this).data('myul', {'date':'28 april'});
更新された jsfiddle はこちら: http://jsfiddle.net/8juvcxqg/
問題は、新しい jQuery ラッパーが作成されるたびに $(this) を呼び出すと、以前のオブジェクトに追加したものが新しいオブジェクトで利用できなくなることです。
$(this) == $(this)
which will returnを使用してテストできますfalse
。
正しい方法は、データAPIを使用することです
$('ul').click(function () {
console.log('test', $(this) == $(this));//will be false since both the times different objects are returned
console.group('Using cached object')
var $this = $(this);//here we use a cached instance of the jQuery wrapper, this will work as long as you have a reference to $this - but is the wrong way
$this.myul = {
'date': '28 april'
}
console.log($this.myul);
console.groupEnd()
console.group('Using data api')
$(this).data('myul', {
'date': '28 april'
});
console.log($(this).data('myul'))
console.groupEnd()
})
デモ:フィドル