I'm encountering a problem with the .data() function in jQuery.
My scenario.
- I insert a span into a content-editable div using atWho (at.js)
- I subscribe to a click event of this span.
- When clicked I do some things which are irrelevant for the element itself.
- When I've done what I want to do. I inset an Object into a data-attribute using .data()
- I now repeat the steps above. However the Object I insert in the data-attribute is now inserted into not only the new element. But also the element I created before.
Both elements have a unique ID. I have not been able to create a jsfiddle as of yet.
I would not be asking this question if I had not looked at it from all possible angles.
I checked if jquery returned multiple elements after click: Not the case. I checked if the data was being appended to both elements: This is the case. I checked if something was wrong with my own code: Not the case.
Jquery states the following: "Store arbitrary data associated with the matched elements or return the value at the named data store for the first element in the set of matched elements.".
Obviously this is not what it does.
Below is the highly simplified version of what I mentioned I do in the above.
$('.item').click(function() {
var dataIwantToAddToDomElement = doSomeStuffRelatedToTheClickedElement(this);
$(this).data(dataIwantToAddToDomElement);
})
function doSomeStuffRelatedToTheClickedElement(element) {
if ($(element).data('nameOfTheStuffIwantToUse')) {
var stuff = $(element).data('nameOfTheStuffIwantToUse');
//do stuff on var
}
return stuff;
}