On Mon, Dec 15, 2008 at 5:07 PM, WebGrunt <bievie...@gmail.com> wrote: > > Hi > > I'm new to jQuery and here's one thing that doesn't make sense. How > do I link an existing function with "this" as argument to a div? > > The function to be called is really simple: > > function test(e) > { > alert(e.id); > //Also tried e.getAttribute("id") or e.attr("id") > }
First, test() is a function of the RegExp object. > Here is what I tried so far inside the $(document).ready(function() > {}); part: > > $("div.someClass").each(function(){ > $(this).test(); > }); > > $("div.someClass").each(function(){ > $(this).test; > }); > > $("div.someClass").each(function(){ > $(this).click(test); > }); > > $("div.someClass").each(function(){ > $(this).click(test()); > }); None of these will work because you're not passing the element as a parameter to the test function. > > Alternatively, I tried: > > function test(strId) > { > alert(strId); > } > > $("div.someClass").each(function(){ > var strId = $(this).attr("id"); > $(this).test(strId); > }); > > $("div.someClass").each(function(){ > var strId = $(this).attr("id"); > $(this).click(test(strId)); > }); Do you want to run the function for each element when the page is loaded, or when the element is clicked on? For the latter, try: function elementTest(e) { alert(e.id); } $(document).ready(function() { $("div.someClass").click(function() { elementTest(this); // note: no $() so you pass the element, not the jQuery object }); }); If you want to fire as they load, use each() $(document).ready(function() { $("div.someClass").each(function() { elementTest(this); }); });