Reputation: 7971
I want add property in jquery object. I am trying to add property in jquery's context.I console the jquery object console.log($(this)), its look like an object. But when i am trying to amend the code is not working fiddle
$('ul').click(function(){
$(this).myul={'date':'28 april'}
console.log($(this))
})
Upvotes: 0
Views: 426
Reputation: 82241
You don't even need jquery for this:
this['myul'] = '"date":"28 april"';
console.log($(this))
Upvotes: 0
Reputation: 8380
You can add data in the data- attributes, in the HTML so an option would be to store:
$(this).data('myul', {'date':'28 april'});
the updated jsfiddle is here : http://jsfiddle.net/8juvcxqg/
Upvotes: 2
Reputation: 388326
The problem is when you call $(this) every time a new jQuery wrapper will be created, so what every you added to the previous object won't be available in the new object.
You can test it using $(this) == $(this)
which will return false
.
The correct way will be is to use the data 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()
})
Demo: Fiddle
Upvotes: 1