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.responsi开发者_开发知识库ve').find('.area.optional').toggle();
});
});
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();
});
});
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.
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.
加载中,请稍侯......
精彩评论