(四)事件处理——(11)更远的巩固(Further consolidation)
(4)事件处理——(11)更远的巩固(Further consolidation)The code optimization weve just completed is an
(4)事件处理——(11)更远的巩固(Further consolidation)
The code optimization we've just completed is an example of refactoring—modifying existing code to perform the same task in a more efficient or elegant way. To explore further refactoring opportunities, let's look at the behaviors we have bound to each button. The .removeClass()method's parameter is optional; when omitted, it removes all classes from the element. We can streamline our code a bit by exploiting this feature, as follows:
$(document).ready(function() {$('#switcher-default').addClass('selected');$('#switcher button').bind('click', function() {var bodyClass = this.id.split('-')[1];$('body').removeClass().addClass(bodyClass);$('#switcher button').removeClass('selected');$(this).addClass('selected');});});
我们注意到,我们需要把一般处理器移动到特殊处理器之上,这个.removeClass()方法需要发生在addclass方法之前,我们可以做到这一点,因为jquery总是按照事件被注册的顺序触发事件。最后,我们可以再一次通过事件处理上下文完全避免特定的事件处理器。上下文关键字this提供了一个dom对象而不是jquery对象,我们可以使用原生的dom属性来决定被点击的元素的id。因此,我们可以为所有的按钮绑定相同的处理器,通过这个处理器为每一个按钮表现不同的行为。代码同上。
The value of the bodyClassvariable will be default, narrow, or large, depending on which button is clicked. Here, we are departing somewhat from our previous code in that we are adding a defaultclass to the <body>when the user clicks <button id="switcher-default">. While we do not need this class applied, it isn't causing any harm either, and the reduction of code complexity more than makes up for an unused class name.
bodyclass变量的值将会根据被点击的按钮来赋予default,narrow,large不同的值。现在我们的代码变的和之前的有些不一样了,当用户点击button Id=switcher-default之后,我们在body上添加了一个defaut类。尽管我们不需要这个类,但是它并没有造成任何坏处,而且降低代码的复杂性弥补了多出一个不被使用的类名的缺点。