(4)事件处理——(10)事件处理上下文(Event handler context)
Our switcher is behaving correctly, but we are not giving the user any feedback about which button is currently active. Our approach for handling this will be to apply the selectedclass to the button when it is clicked, and remove this class from the other buttons. The selectedclass simply makes the button's text bold:
$(this).addClass('selected');把这行代码放在这三个处理器的每一个中,将会在按钮被点击以后添加上这个类。为了移除其他按钮的这个类,我们可以借助jquery的隐式迭代的特点,写下下面这样的代码段:
$('#switcher button').removeClass('selected');这行将会移除风格切换器内部的每一个按钮的类。We should also add the class to the Defaultbutton when the document is ready. So, placing these in the correct order, we have the following code snippet:
$(document).ready(function() {$('#switcher-default').addClass('selected').bind('click', function() {$('body').removeClass('narrow').removeClass('large');});$('#switcher-narrow').bind('click', function() {$('body').addClass('narrow').removeClass('large');});$('#switcher-large').bind('click', function() {$('body').removeClass('narrow').addClass('large');});$('#switcher button').bind('click', function() {$('#switcher button').removeClass('selected');$(this).addClass('selected');});});
代码同上。
This optimization takes advantage of three jQuery features we have discussed. First, implicit iterationis, once again, useful when we bind the same clickhandler to each button with a single call to .bind(). Second, behavior queuingallows us to bind two functions to the same click event, without the second overwriting the first. Lastly, we're using jQuery's chainingcapabilities to collapse the adding and removing of classes into a single line of code each time.
这种优化方法使用了我们讨论过的三个jquery特点的优势。首先,在一次,我们使用隐式继承,当我们单单调用.bind()来为每一个按钮绑定click事件的时候,这是很有用的。第二,行为序列按我们在同一个点击事件上绑定了两个函数,而不会担心第二个函数会吧第一个覆盖。最后,我们使用了jquery的链式能力,在一行代码中用简练的代码实现了添加和移除类。