Sorry for this very basic JQuery question. I created ‘mytest’ jquery function like this:
jQuery.fn.mytest = function () {
alert($(this).attr('id'))
}
Now if I call it like this everything is perfect:
$("#someid").mytest();
It alerts “someid”. But if I do something like this:
$("#someid, #anotherid, #moreids").mytest();
this function only alerts “someid”. Of course “anotherid” and “moreids” exist.
Why mytest() is not working and what is the right code for this function?
Your code is adding a “plugin” to jQuery that makes your function available on jQuery instances. The reason you’re only seeing one ID in your function is that you’re using
attr, which only retrieves the first element’s attribute. (Also, you really don’t needattrto get anidvalue.)Your function should look something like this (live copy):
…to show the
idvalues (if any) of each element in the currently-matched set.Or you could do it with a simple loop rather than with
jQuery.map(live copy):Also, note that within a jQuery plug-in function,
thisis the current jQuery instance, so you don’t need (or want) to pass it through$()to create a jQuery wrapper around the element (you do that in event handlers, not plug-ins). So when I dothis.lengthin the second example above, I’m using thelengthproperty of the jQuery instance that we’re currently operating on. When I index intothisusing bracketed notation (elm = this[index];), I’m indexing into the jQuery instance’s matched set of elements (like thegetmethod, but more directly).