Use jQuery to reference an anchor tag in the same div as self
I have a jQuery function that binds the click event of any element on my page with the class name 'foo'.
$('.foo').click(function () { etc.
Whilst inside this function I want to reference another element that exists alongside the currently bound element - inside开发者_开发问答 the same div but with the class name 'bar'.
How do I go about referencing 'bar' based on it's proximity, within the same div?
If the elements are at same level you can use siblings i.e.:
$(this).siblings(".bar")
If the hierarchy is different then try this:
$(this).closest("div").find(".bar")
Like this if bar is the next sibling after foo:
<div>
<div class="foo"></div>
<div class="bar"></div>
</div>
$('.foo').click(function () {
var bar = $(this).next('.bar');
});
Like this if bar is the previous sibling after foo:
<div>
<div class="bar"></div>
<div class="foo"></div>
</div>
$('.foo').click(function () {
var bar = $(this).prev('.bar');
});
Like this if bar can be either the previous or next sibling of foo:
$('.foo').click(function () {
var bar = $(this).siblings('.bar');
});
OR
$('.foo').click(function () {
var bar = $('bar', $(this).parent());
});
$('.bar', this)
<-- like that (if bar
is within foo
)
$(this).closest('.bar')
<-- like that (if bar
is near foo
)
精彩评论