How to create a function that is
I am not a programmer, I just a web designer with a bit of programmatic skills and I am asking for your help to learn a bit more about jquery/javascript.
I have a singl开发者_高级运维e function which is calling 2 different divs (test1 & test2)
myFunction ($("#test1"));
myFunction ($("#test2"));
I want to try to achieve instead something similar to
myFunction ($("#test1") $("#test2"));
Because I want to try to use one call, to call multiple divs. As well my problem is that my ipotetical myFunction should look like this:
myFunction (param1, param2){ if(typeof param2 == "undefined"){param2 = $(window)}; // do something}
I have no idea on how to create a multiple call to a function for doing the same action but on different elements, and with the fact that I could have multiple parameters, it doesn't make it easy for me.
Any suggestion on how to do it? or some resource where I could read for? thx, in advance! :)
myFunction($("#test1, #test2, #test3"));
Have a look at http://api.jquery.com/multiple-selector/
Another way, by making a plugin:
<div>Hello</div>
<div class="blah">Another</div>
<div class="foo">And another</div>
$.fn.myFunc = function() {
// loop over all matches
this.each(function() {
// do something with each match
alert($(this).text());
});
return this;
};
// call it on any set of elements like this
$("div").myFunc();
Demo: http://jsfiddle.net/sbcvg/
精彩评论