views:

475

answers:

4
+1  A: 
$( 'td:first-child', $( this ).parents ( 'tr' ) ).html ();

This will select the first TD element (:first-child filter) in the parent TR of the image. parents() returns all parents of the element, and we filter the parents so that only TR elements are returned.

Also try writing your image like so:

<img src="bobsmith.png" onclick="doSomething(this)" />

and your function like so:

function doSomething ( imgEl ) {
}

and use imgEl instead of this

Jan Hančič
I'm still getting nulls with this. I suspect that the `this` link is not resolving the originating object.
Mike
I just updated my answer, try now.
Jan Hančič
Thanks. Looks like I may have to go in and hack the code rendering the table. :) I was hoping to not have to do this.
Mike
why are putting the `onclick` in your element? and not bind it using jQuery? curious
Reigel
@Reigel I am not responsible for the component rendering the table. I thought it more efficient to reuse the `onclick` call rather than continually bind with use of jQuery's Live module.
Mike
+1  A: 
$('tr td:last-child img').click(function(){

    alert($('td:first-child',$(this).closest('tr')).text());

});
Reigel
+1  A: 

I would set up an event using jQuery, but that's totally up to you.

$("table td:last img").click(function() {
    var firstTd = $(this).parents("tr").find("td:first").html();
    alert("you clicked person #" + firstTd);
}); 

No matter what, you can still use this example with your own code:

function doSomething()
{
    var firstTd = $(this).parents("tr").find("td:first-child").html();
    alert("you clicked person #" + firstTd);
}

You're right. 'this' is not being passed, you need to edit the html to make that work. Or just use jQuery instead as show above.

Kordonme
While `:last` matches only a single element: the last picked element, `last-child` matches more then one: One for each parent.
Reigel
@Reigel: You're absolutely right. I've changed the answer. Thanks.
Kordonme
A: 

maybe this will help somebody. This is just a part of the whole article here.

The difference

If you want to use this for accessing the HTML element that is handling the event, you must make sure that the this keyword is actually written into the onclick property. Only in that case does it refer to the HTML element the event handler is registered to. So if you do

element.onclick = doSomething;
alert(element.onclick)

you get

function doSomething()
{
    this.style.color = '#cc0000';
}

As you can see, the this keyword is present in the onclick method. Therefore it refers to the HTML element.

But if you do

<element onclick="doSomething()">
alert(element.onclick)

you get

function onclick()
{
    doSomething()
}

This is merely a reference to function doSomething(). The this keyword is not present in the onclick method so it doesn't refer to the HTML element.

Reigel