2010-01-01 85 views

回答

6

它仅打开一个文本容器,因为点击事件绑定到与div.trigger匹配的每个单独元素。当您点击其中一个匹配元素时,您只需点击一个匹配元素,而不是全部3个。点击回调函数内部的$(this)的用法仅引用点击元素

的代码也可以通过简单地链接调用一起被清理一点点:

$('div.trigger').click(function() { 
    if ($(this).hasClass('open')) { 
     $(this).removeClass('open').addClass('close').next().slideDown(100); 
    } else { 
     $(this).removeClass('close').addClass('open').next().slideUp(100); 
    } 
    return false; 
}); 
6

当您使用类别触发器单击div时,它将使用next()打开触发器旁边的元素。类名不重要,因为它在$(this)上运行,这是点击元素。

打开下面的div后,它会为自己分配一个“打开”类,以便下次用户点击它时可以采取不同的行为。

该页面的代码是这样的:

$('div.trigger').click(function() { 
    if ($(this).hasClass('open')) { 
     $(this).removeClass('open'); 
     $(this).addClass('close'); 
     $(this).next().slideDown(100); 
     return false; 
    } else { 
     $(this).removeClass('close'); 
     $(this).addClass('open'); 
     $(this).next().slideUp(100); 
     return false; 
    }    
}); 

其中,翻译成英文,是这样的:

/* 
When .trigger is clicked: 
    If it has a class named 'open': 
     Remove that class, 
     and add a class named 'close'. 
     Slide down the element next to this element in 100 milliseconds. 
     Prevent other actions from taking place. 
    If it hasn't got a class named 'open': 
     Remove class 'close', 
     and add class 'open'. 
     Slide up the element next to this element in 100 milliseconds. 
     Prevent other actions from taking place. 
+0

+1的伪代码 – 2010-01-01 20:24:20

0

$('div.trigger').click(function()...this...意味着,当你点击一个trigger类元素时,函数仅适用于this,这是您单击的元素。当你点击它时,它会得到一个新课程,open,这给了它新的属性。

0

这是因为你用$运行(本),转换按钮单击。

0

在源代码中的函数$(document).ready()附加一个新click功能$('div.trigger')元件:

$('div.trigger').click(function() { 
    // ... 
}); 

个体电流)DIV通过$(this)表示的功能。

if ($(this).hasClass('open')) { 
    // ... 
}   

概括地说,每个div有分配了相同的功能和功能码被写入在当前的角度(点击)DIV。

2

一些行内注释可能解释清楚:

#If we have divs with the class 'trigger' 
if($('div.trigger').length > 0) { 
    # Attach logic to the click event of each 
    $('div.trigger').click(function() { 
    # If this has the class 'open' already 
    if ($(this).hasClass('open')) { 
     # Remove the class 'open' 
     $(this).removeClass('open'); 
     # Add the class 'close' 
     $(this).addClass('close'); 
     # And slide down the next div 
     $(this).next().slideDown(100); 
     # Return False 
     return false; 
    } else { 
     # If this didn't have 'open', remove 'close' 
     $(this).removeClass('close'); 
     # Add the class 'open' 
     $(this).addClass('open'); 
     # And slide up the next div 
     $(this).next().slideUp(100); 
     # Return false 
     return false; 
    }   
    }); 
}