views:

243

answers:

2

I have a bunch of images on my ASP.NET page like so:

for (int i = 0; i < 3; i++)
{
    Image image = new Image();
    image.ID = "UpdateStatus";
    image.CssClass = "imageCss";
    image.ImageUrl = "Bump.GIF";
    this.Controls.Add(image);
}

I want to loop through each image.

Why does this not work? i.e. "Function 1" is outputted but "Function 2" is not

$(document.body).click(function () {
    console.log('Function 1');

    $('imageCss').each(function(){
        console.log('Function 2');
    });
});

Why does this not work? i.e. "Function 1" is outputted and "Function 2" outputted ONCE. Why not 3 times?

$(document.body).click(function () {
    console.log('Function 1');

    $(''#UpdateStatus'').each(function(){
        console.log('Function 2');
    });
});

This works fine BUT i cannot access 'this', it is NULL. I need to be able to reference the current image.

$(document.body).click(function () {
    console.log('Function 1');

    $.each('#UpdateStatus', function() { //Or when I use 'imageCss'
        console.log('Function 2');        
        console.log(this);
    });
});
+10  A: 

(1) Your jQuery call $('imageCss') isn't a valid selector. You need to prefix the classname with '.' to denote that you want to select elements with the class "imageCss":

$('.imageCss')

(2) IDs must be unique. When you set Control.ID = "foo" on the server in ASP.NET, that is setting the server-side ID of the control. The client-side ID generated in the HTML will be a unique, long, ugly string like ctl00_ctl01_pnlMain_foo1. Your best option is to use class selectors. You can apply multiple classes to a single element by using a space to separate them:

myImage.CssClass = "image otherclass";

Both $('.image') and $('.otherclass') will correctly select the element.

(3) this does not exist because of closures. Functions are executed in the context of the object that invokes the function, so this will be that object.

Or, in your case it doesn't really look like your function is executing within the context of any object, so I'm not sure what you're expecting this to be.

Rex M
A: 

to reference the current image do something like:

$.each('#UpdateStatus', function(i, val) {
    console.log('Function 2');        
    console.log(val);
});
Sam Hasler