Object consisting of jQuery element

current code

I created a function to do something about assembling jQuery elements:

var collection = $([]); //empty collection 

I add them with:

 collection = collection.add(e); 

and delete with:

 collection = collection.not(e); 

This is a fairly simple solution, works great.

Problem

Now I would like to have an object consisting of various settings set for any jQuery element, i.e.:

 function addObject(e){ var o = { alpha: .6 //float base: {r: 255, g: 255, b: 255} //color object } e.data('settings', o); } 

But when I pass the jQuery object / element to the function (i.e. as e ), calling e.data does not work, although that would be a simple and really nice solution.

Question

If I have a โ€œcollectionโ€ of jQuery elements, what is the easiest way to store some data for each element in the set?

+4
source share
4 answers

Ah, I decided it already :)

latest version:

This is somewhat simplified code:

 function setData(e,key,data){ if(typeof(e)==string){ e = $(e); } $(e).data(key,data); } 

Decision

The problem was that I wanted to keep the ability to add an element via $('element') , 'element' or $(this) , so I had to add a typeof check before setting up the data - just like jQuery works.

if I add an element as soon as the selector , it is $(e) , if I add a jQuery object , it is e :

 function setData(e,key,data){ if(typeof(e)==string){ $(e).data(key,data); }else{ e.data(key,data); } } 

So, you all will get an advantage, and I will take myself the winner in two days, so anyone who stumbles on this question will know what to do (clearly, verified, working:]) and why :)

Edit : note: This is probably not the final version. I read additional documentation, so this setData function supports all types supported by jQuery.add .

+2
source

If these "elements" are valid DOM elements (nodes), then you canโ€™t just use $(e).data(...) ?

+2
source

I think the problem is that you are dealing with the collection in this way, and you are adding an element ... if it has not been wrapped by jquery, but it will not. Thus, when re-accessed, it is simply an unprocessed element.

If I am true to this line of thinking, e is an infact dom / node element (or its string representation), then a simple $(e) should give you access to its data method.

 function addObject(e){ var o = { alpha: .6 //float base: {r: 255, g: 255, b: 255} //color object } $(e).data('settings', o); } 
+1
source

Is it because you missed the comma between your two properties?

  var o = { alpha: .6 <-- here base: {r: 255, g: 255, b: 255} } 

(I doubt it, but I felt the need to point it out)

This works and is a bit ahead (at least IMO):

  $.fn.addObject = function(){ var o = { alpha: .6, //float base: {r: 255, g: 255, b: 255} //color object } $(this).data('settings', o); }; // simple test $("div").addObject(); alert($("div").data("settings").alpha); // alerts 0.6 
+1
source

Source: https://habr.com/ru/post/1305662/


All Articles