Reputation: 4918
I have a table with a couple of rows:
<tr class='data'>
<td class='img'><img class='thumbnail' src='ProductImages/img_1894_72.jpg'/></td>
<td class='bc_img'><img class='thumbnail' src='ProductImages/img_1893_72.jpg'/></td>
</tr>
<tr class='data'>
<td class='img'><img class='thumbnail' src='ProductImages/img_1318_72.jpg'/></td>
<td class='bc_img'><img class='thumbnail' src='ProductImages/img_1646_72.jpg'/></td>
</tr>
The images in the cells are thumbnail images (the 72 in the name specifies a 72px width). I want to write some jQuery that will let me click the second td in either row, sense which of the two rows I chose, and replace the src image in that row with a larger version of the same image, i.e., replace the 72 in the src name with a 300.
My problem is getting from the clicked td to the raw img node within that td. I've been playing with:
$("td.bc_img").click(function () {
console.log("1. this is " , this);
imgNode = $(this).find('img').get();
console.log("2. imgNode is " , imgNode);
console.log("3. imgNode.src is " , imgNode.src);
var thumbSrc = ?; // not sure how to get this
var bigImgSrc = thumbSrc.replace(/_72\.jpg/, "_900.jpg");
});
And that produces the console output:
But that doesn't seem to be what I need. I think I need to get something that looks like:
<img class="thumbnail" src="ProductImages/img_1893_72.jpg">
before I can add .src to it and modify the src.
Thanks for any help.
Upvotes: 1
Views: 78
Reputation: 679
I changed some lines of code to get the required src and change the attribute
$("td.bc_img").click(function () {
console.log('rw');
imgNode = $(this).find('img').attr('src');
console.log("The image node source is " , imgNode);
$(this).find('img').attr('src', 'put your replacement url here');
});
The fiddle URL is http://jsfiddle.net/8fd8Q/1/
Upvotes: 1
Reputation: 708056
The key is that you use $(this).find("img")
to find the image in the cell that received the click.
$("td.bc_img").click(function () {
var img = $(this).find("img").get(0);
img.src = img.src.replace(/_72\.jpg/, "_900.jpg");
});
Upvotes: 2
Reputation: 12025
Use get(0)
to get the DOM object for the image:
imgNode = $(this).find('img').get(0);
Now I believe the value of thumbSrc
can be set to imgNode.src
.
Upvotes: 1
Reputation: 298532
Your selector is returning an array of elements (notice the square brackets around the prettified console text), which has no src
property. Get the first element of that array (or use .get(0)
, which does the same thing):
> $('img').get();
[img]
> $('img').get()[0];
<img src="foo.jpg" />
> $('img').get(0);
<img src="foo.jpg" />
You can also get the src
attribute out of the jQuery object using .attr('src')
Upvotes: 1