Quickest way to find an element with jQuery
Given the following html:
<tr>
<td>Content</td>
<td>Content</td>
<td>Content</td>
<td><img id="imgProductPurchased" runat="server" visible="true" alt="Product Purchased" title="Product Purchased" src="/sitecore/shell/Themes/Standard/Applications/16x16/checkbox.png" /></td>
<td>
<asp:PlaceHolder ID="plhPurchased" runat="server">
<span class="roundButton roundButtonLarge"><a id="hypPurchased" class="registryPurchased" href="#" title="Mark product as purchased" runat="server"><span>
<em class="registryPurchased"></em>Purchased</span></a> <span class="buttonEndLarge">
</span></span>
</asp:PlaceHolder>
</td>
</tr>
<tr>
Repeats above
</tr&开发者_StackOverflow中文版gt;
I have a click event on "hypPurchased". When that event fires, I need to access the plhPurchased element, and "imgProductPurchased" elements of THAT row.
EDIT:
I should have stated that this is being built with ASP.NET, and as such, the id's are all unique.
If the click event is on the particular row and the element is a child of that row, you can use context to get the result.
$(".myRow").click(function() {
var somethingFromMyRow = $(".myChildClassName", this).text();
alert(somethingFromMyRow);
});
Please note, you shouldn't be duplicating the same ID anywhere on your page, so the example I have supplied uses a class name instead - so imagine you have HTML like this for your example.
<tr class="myRow">
<td><span class="myChildClassName">Some Text In Row 1</span></td>
<td>More Stuff</td>
</tr>
<tr class="myRow">
<td><span class="myChildClassName">Some Text In Row 2</span></td>
<td>More Stuff</td>
</tr>
<tr class="myRow">
<td><span class="myChildClassName">Some Text In Row 3</span></td>
<td>More Stuff</td>
</tr>
id
's can't be duplicated in HTML,
Anyway, what you need to do is get to a parent element (go up in the hierarchy until you get the parent element that encompasses the "current" row), then you run the query against it:
jQuery( your_query_string, parent )
Where parent is something you can get using:
parent = query.parent()
For instance:
function click_handler(element)
{
parent = jQuery(element).parent()
name = jQuery(".name", parent)
// do stuff
}
name = jQuery(".name", parent)
will get all elements with class name
under the parent
element.
has Hasen said, you cant duplicate id's in html.
so, apply a class to "plhPurchased" and then:
at the hypPurchased you put onclick="yourFuntion(this)"
function yourFuntion(elem)
{
var tr=$(elem).closest('tr');
var _imgProductPurchased = tr.find('img');
// if you have more then a img per row, you should apply a class to the image to and get it by:
// tr.find('.imgClass');
var _plhPurchased=tr.find('.thatClassYouApplyed');
}
精彩评论