如何从'click'函数中定位$ this(来自'each'上下文).我想删除尴尬的.parents().find()代码.
$('.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();
});
});
Run Code Online (Sandbox Code Playgroud)
将其保存在命名(非特殊)变量中:
$('.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();
});
});
Run Code Online (Sandbox Code Playgroud)
解决方案当然与这里的其他人相同,但我认为使用这种语法更清晰,并且将实现与您现在使用的代码相同的效果。
$('.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);
});
Run Code Online (Sandbox Code Playgroud)
我们可以使用 jQuery 1.4 中引入的新语法来更干净地完成此操作,而不是插入 HTML 字符串,并且无需您现在使用的混乱的内联事件处理程序。
| 归档时间: |
|
| 查看次数: |
1105 次 |
| 最近记录: |