Reputation: 1010
How do I target $this (from 'each' context) from inside 'click' function. I want to remove awkward .parents().find() code.
$('.layout.responsive').each(function () {
$('.area.optional', this).before('<a href="#" class="toggle_responsive" onClick="return false">Show details</p>').hide();
$('.toggle_responsive', this).click(function () {
$(this).parents('.layout.responsive').find('.area.optional').toggle();
});
});
Upvotes: 5
Views: 1126
Reputation: 50115
The solution is of course the same as everybody else's here, but I think using this syntax is much cleaner and will accomplish the same as the code you're using right now.
$('.layout.responsive').each(function () {
var ar = $(this).find('.area.optional').hide(),
showDetail = $('<a />', {
href: '#',
class: 'toggle_responsive',
text: 'Show details',
click: function(){
ar.toggle();
return false;
}}).insertBefore(ar);
});
Instead of inserting in a HTML string, we can use the new syntax introduced in jQuery 1.4 to do this much more cleanly, and without the messy inline event handler you're using right now.
Upvotes: 3
Reputation: 318518
You can simply store it in a variable:
$('.layout.responsive').each(function () {
var $elem = $('.area.optional', this).before('<a href="#" class="toggle_responsive">Show details</p>').hide();
$('.toggle_responsive', this).click(function(e) {
e.preventDefault();
$elem.toggle();
});
});
Also note the e.preventDefault();
call which does pretty much what your onclick="return false;"
did but in a much cleaner way.
Upvotes: 4
Reputation: 138082
Save it in a named (non-special) variable:
$('.layout.responsive').each(function () {
var area = $('.area.optional', this).before('<a href="#" class="toggle_responsive" onClick="return false">Show details</p>').hide();
$('.toggle_responsive', this).click(function () {
$(area).toggle();
});
});
Upvotes: 7