bootstrap源码分析之下拉菜单 (+function ($) { "use strict";}(window.jQuery);全面分析)

<div class="dropdown">
  <a id="dLabel" data-target="#" href="http://example.com" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
    Dropdown trigger
    <span class="caret"></span>
  </a>

  <ul class="dropdown-menu" aria-labelledby="dLabel">
    ...
  </ul>
</div>

两个API①data-toggle属性②javascript---$(‘.dropdown-toggle‘).dropdown()

bootstrap.js中可以找到dropdown.js的内容如下

  1 /* ========================================================================
  2  * Bootstrap: dropdown.js v3.3.5
  3  * http://getbootstrap.com/javascript/#dropdowns
  4  * ========================================================================
  5  * Copyright 2011-2015 Twitter, Inc.
  6  * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE)
  7  * ======================================================================== */
  8
  9
 10 +function ($) {
 11   ‘use strict‘;
 12
 13   // DROPDOWN CLASS DEFINITION
 14   // =========================
 15
 16   var backdrop = ‘.dropdown-backdrop‘
 17   var toggle   = ‘[data-toggle="dropdown"]‘
 18   var Dropdown = function (element) {
 19     $(element).on(‘click.bs.dropdown‘, this.toggle)
 20   }
 21
 22   Dropdown.VERSION = ‘3.3.5‘
 23
 24   function getParent($this) {
 25     var selector = $this.attr(‘data-target‘)
 26
 27     if (!selector) {
 28       selector = $this.attr(‘href‘)
 29       selector = selector && /#[A-Za-z]/.test(selector) && selector.replace(/.*(?=#[^\s]*$)/, ‘‘) // strip for ie7
 30     }
 31
 32     var $parent = selector && $(selector)
 33
 34     return $parent && $parent.length ? $parent : $this.parent()
 35   }
 36
 37   function clearMenus(e) {
 38     if (e && e.which === 3) return
 39     $(backdrop).remove()
 40     $(toggle).each(function () {
 41       var $this         = $(this)
 42       var $parent       = getParent($this)
 43       var relatedTarget = { relatedTarget: this }
 44
 45       if (!$parent.hasClass(‘open‘)) return
 46
 47       if (e && e.type == ‘click‘ && /input|textarea/i.test(e.target.tagName) && $.contains($parent[0], e.target)) return
 48
 49       $parent.trigger(e = $.Event(‘hide.bs.dropdown‘, relatedTarget))
 50
 51       if (e.isDefaultPrevented()) return
 52
 53       $this.attr(‘aria-expanded‘, ‘false‘)
 54       $parent.removeClass(‘open‘).trigger(‘hidden.bs.dropdown‘, relatedTarget)
 55     })
 56   }
 57
 58   Dropdown.prototype.toggle = function (e) {
 59     var $this = $(this)
 60
 61     if ($this.is(‘.disabled, :disabled‘)) return
 62
 63     var $parent  = getParent($this)
 64     var isActive = $parent.hasClass(‘open‘)
 65
 66     clearMenus()
 67
 68     if (!isActive) {
 69       if (‘ontouchstart‘ in document.documentElement && !$parent.closest(‘.navbar-nav‘).length) {
 70         // if mobile we use a backdrop because click events don‘t delegate
 71         $(document.createElement(‘div‘))
 72           .addClass(‘dropdown-backdrop‘)
 73           .insertAfter($(this))
 74           .on(‘click‘, clearMenus)
 75       }
 76
 77       var relatedTarget = { relatedTarget: this }
 78       $parent.trigger(e = $.Event(‘show.bs.dropdown‘, relatedTarget))
 79
 80       if (e.isDefaultPrevented()) return
 81
 82       $this
 83         .trigger(‘focus‘)
 84         .attr(‘aria-expanded‘, ‘true‘)
 85
 86       $parent
 87         .toggleClass(‘open‘)
 88         .trigger(‘shown.bs.dropdown‘, relatedTarget)
 89     }
 90
 91     return false
 92   }
 93
 94   Dropdown.prototype.keydown = function (e) {
 95     if (!/(38|40|27|32)/.test(e.which) || /input|textarea/i.test(e.target.tagName)) return
 96
 97     var $this = $(this)
 98
 99     e.preventDefault()
100     e.stopPropagation()
101
102     if ($this.is(‘.disabled, :disabled‘)) return
103
104     var $parent  = getParent($this)
105     var isActive = $parent.hasClass(‘open‘)
106
107     if (!isActive && e.which != 27 || isActive && e.which == 27) {
108       if (e.which == 27) $parent.find(toggle).trigger(‘focus‘)
109       return $this.trigger(‘click‘)
110     }
111
112     var desc = ‘ li:not(.disabled):visible a‘
113     var $items = $parent.find(‘.dropdown-menu‘ + desc)
114
115     if (!$items.length) return
116
117     var index = $items.index(e.target)
118
119     if (e.which == 38 && index > 0)                 index--         // up
120     if (e.which == 40 && index < $items.length - 1) index++         // down
121     if (!~index)                                    index = 0
122
123     $items.eq(index).trigger(‘focus‘)
124   }
125
126
127   // DROPDOWN PLUGIN DEFINITION
128   // ==========================
129
130   function Plugin(option) {
131     return this.each(function () {
132       var $this = $(this)
133       var data  = $this.data(‘bs.dropdown‘)
134
135       if (!data) $this.data(‘bs.dropdown‘, (data = new Dropdown(this)))
136       if (typeof option == ‘string‘) data[option].call($this)
137     })
138   }
139
140   var old = $.fn.dropdown
141
142   $.fn.dropdown             = Plugin
143   $.fn.dropdown.Constructor = Dropdown
144
145
146   // DROPDOWN NO CONFLICT
147   // ====================
148
149   $.fn.dropdown.noConflict = function () {
150     $.fn.dropdown = old
151     return this
152   }
153
154
155   // APPLY TO STANDARD DROPDOWN ELEMENTS
156   // ===================================
157
158   $(document)
159     .on(‘click.bs.dropdown.data-api‘, clearMenus)
160     .on(‘click.bs.dropdown.data-api‘, ‘.dropdown form‘, function (e) { e.stopPropagation() })
161     .on(‘click.bs.dropdown.data-api‘, toggle, Dropdown.prototype.toggle)
162     .on(‘keydown.bs.dropdown.data-api‘, toggle, Dropdown.prototype.keydown)
163     .on(‘keydown.bs.dropdown.data-api‘, ‘.dropdown-menu‘, Dropdown.prototype.keydown)
164
165 }(jQuery);


问题一:

+function ($) { "use strict";

}(window.jQuery); 怎么理解?

解释:

匿名函数闭包

我们先来理一理函数表达式和函数声明的区别

函数表达式:The function can be anonymous function, also can have the function name, but in fact this function cannot be used directly, only through the expression on the left side of the variable a to call.  函数可以是米名函数,也可以有函数名,但是这种函数无法直接使用,只有通过表达式左侧的变量来调用。

var a = function(){
  alert(‘Function expression‘);
}
var b = new a();

函数声明Must have the function name. 必需要有函数名 

function a(){
  alert(‘Function declaration‘);
}
a();

This is a An anonymous function 下面是一个匿名函数

function () {

}

The unary operator + into function expression.一元操作符+和函数表达式

Can also use the - ~! Other unary operators or brackets, the purpose is to guide the parser, near the specified operator is an expression.也可以使用如-,~,!这种其它的一元操作符或者括号,目的是告诉解析器在这些特定操作符附近的是一个表达式(注意,JS将function当作一个函数声明的开始,而函数声明后面不能跟圆括号直接进行调用,所以有的时候想办法将函数声明转化为函数表达式)

The following are three classical methods 三种典型方式进行上述转换

+function () { 

};

(function () {

});

void function() {

};


The efficiency of these three kinds of

Operators addition and subtraction counter, operator "~" (bit reverse) the definition in the EMCAScript5: according to operator binding statement; the old value into a 32 bit integer; execution operator after the statement; conversion of the line for 32 bit and returns the result.

"()"Group operators: returns the expression results in the execution of the.

void: According to operator binding statement execution, return undefined. 
The group operator also needs to perform the statement and returns the value returned by the contrast statement block, void multiple access block operation, thus the performance of void in this case is better than the group of operators.

 吧拉粑粑拉粑粑拉吧拉吧拉吧没看明白不好意思!



Through the end of the () to call and run 通过在表达式末尾加()运行

+function () { 

}();

(funtion () {

})();

Parameter passing, in order to avoid the $and other library or template that conflict, window.jQuery passed as parameters.

参数传递,为了避免$和其他库或模板发生冲突,jquery用这种方式起作用

+function (x) {
    console.log(x);
}(3);

+function ($) {

}(window.jQuery); 

Another advantage is that, within the scope of the JS interpreter, can quickly find $object than this method.

 其它优势在于,在JS解释器中,这种方式下的效率更高

$(function(){  

});

There is a way, to avoid naming conflicts.

避免冲突的另一种方式

var j = jQuery.noConflict();
j(‘#someDiv‘).hide();
$(‘someDiv‘).style.display = ‘none‘;// Other libraries$

A look of writing something like the code. This code initializes the jQuery code in the DOM loading is complete.

这种写法,代码将在DOM加载完毕时初始化Jquery代码

$(function(){ 

}); 

This is equivalent to the

和下面这种写法作用相同

$(document).ready(function(){
// Initialize the jQuery code in the DOM loading is complete. 
});
Different from 和这种不同
$(window).load(function(){
// In the picture, the media file is loaded, the initialization of jQuery code.
});

In strict mode 严格模式下的情况我暂时先不研究了,等日后水平上来再进一步学习

The establishment of "strict mode", mainly in the following: norms, efficiency, safety, facing the future

  Remove the Javascript grammar some unreasonable, not rigorous, reduce some strange behavior;

  - remove some safety code operation code, ensure operation safety,

  - to improve the compiler efficiency, increase running speed,

  - in order to pave the way for future versions of Javascript.

Enter "sign in strict mode", is the following statement:   

"use strict";

The old version of the browser will send it as an ordinary string, ignore them.

The "use strict" in the first line of the script file, the script will be "strictly" mode of operation.

If this statement is not in the first row, is invalid, the script is run in "normal mode".

If the code files of different patterns was merged into one document, this requires special attention.

(strictly speaking, as long as the front is not to produce practical results of the sentence, "use strict" may not be in the first line, such as direct as in an empty semicolon. )

<script>
  "use strict";
  console.log("This is strict mode. ");
</script>
<script>
 console.log("This is the normal mode. ");
</script>

The "use strict" in the first line of the function body, the entire function to "strict" mode of operation.

function strict(){
  "use strict";
  return "This is strict mode. ";
}
function notStrict() {
  return "This is the normal mode. ";
}

Because calling the method above is not conducive to the files, so it is better, the following method, the script file in an anonymous function is executed immediately.

+function (){  "use strict";

}();

The scope of strict mode constraint

Var declare variables. In strict mode, variable must use the VaR command to display the statement, and then use the.

"use strict";
v = 1; // Error, V is not a statement
for(i = 0; i <2; i++) { // Error, I is not a statement

}

Numbers don‘t add 0. Disable the octal algorithm because... Because the octal is not included in the ECMAScript, the digital front 0 will change the meaning of numbers, JS will think is an octal number, thus error.

"use strict";
var sum = 015 + // Error! syntax error
          197 +
          142;

Do not allow the function non top, it is not allowed to function nesting. ECMAScript5 (or ECMAScript3) are not allowed.

"use strict";
if (true){
  function f() { } // Error! syntax error
  f();
}

for (var i = 0; i <5; i++){
  function f2() { } // Error! syntax error
  f2();
}

function baz(){ // kosher
  function eit() { } // also kosher
}

Don‘t use these words do variables or parameters implements, interface, let, package, private, protected, public, static, yield. In strict mode as the reserved keywords. Future ECMAScript seems to cut into the pre.

function package(protected){ // Error!
  "use strict";
  var implements; // Error!

  interface: // Error!
  while (true){
    break interface; // Error!
  }

  function private() { } // Error!
}
function fun(static) { ‘use strict‘; } // Error!

Console implementation of strict mode returns undefined

(function(){ return this; })() Window {top: Window, window: Window, location: Location, external: Object, chrome: Object…}

(function(){ ‘use strict‘; return this; })()undefined

There are other examples

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions_and_function_scope/Strict_mode?redirectlocale=en-US&redirectslug=JavaScript%2FReference%2FFunctions_and_function_scope%2FStrict_mode

Document ready immediately

!function ($) {

  $(function(){

  })

}(window.jQuery)


问题二:


				
时间: 2024-11-05 20:29:59

bootstrap源码分析之下拉菜单 (+function ($) { "use strict";}(window.jQuery);全面分析)的相关文章

Appium Android Bootstrap源码分析之控件AndroidElement

通过上一篇文章<Appium Android Bootstrap源码分析之简介>我们对bootstrap的定义以及其在appium和uiautomator处于一个什么样的位置有了一个初步的了解,那么按照正常的写书的思路,下一个章节应该就要去看bootstrap是如何建立socket来获取数据然后怎样进行处理的了.但本人觉得这样子做并不会太好,因为到时整篇文章会变得非常的冗长,因为你在编写的过程中碰到不认识的类又要跳入进去进行说明分析.这里我觉得应该尝试吸取著名的<重构>这本书的建议

Appium Android Bootstrap源码分析之命令解析执行

通过上一篇文章<Appium Android Bootstrap源码分析之控件AndroidElement>我们知道了Appium从pc端发送过来的命令如果是控件相关的话,最终目标控件在bootstrap中是以AndroidElement对象的方式呈现出来的,并且该控件对象会在AndroidElementHash维护的控件哈希表中保存起来.但是appium触发一个命令除了需要提供是否与控件相关这个信息外,还需要其他的一些信息,比如,这个是什么命令?这个就是我们这篇文章需要讨论的话题了. 下面我

[Bootstrap 源码]——bootstrap源码之初始化

bootstrap源码之初始化 我们先来分析normalize.less编译后的源码,我们知道normalize.css是一个专门将不同浏览器的默认css特性设置为统一效果的css库,它和reset.css还是有区别的,normalize.css并不是简单的重置了所有的样式,而是有针对的修改,同时也保留了标签的语义化. 技能一: html { font-family: sans-serif; -webkit-text-size-adjust: 100%; //防止IOS系统方向改变(特别是手持设

Bootstrap历练实例:下拉菜单插件方法的使用

<!DOCTYPE html><html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>Bootstrap历练实例:下拉菜单插件方法的使用</title> <meta charset="utf-8" /> <meta name="v

Bootstrap 源码解析

Bootstrap 源码解析 1.Bootstrap的作用域 2.Bootstrap的类定义 3.Bootstrap的插件定义 4.Bootstrap的事件代理 5.Bootstrap的对象数据缓存 6.Bootstrap的防冲突 7.作用域外如何使用Button类 8.Bootstrap的单元测试 Bootstrap的作用域 Bootstrap每个插件都定义在下面这段作用域代码中: 请看<IIFE>和<严格模式>编译环境. 在插件的作用域之外,全局范围执行代码的第一行,检测了jQ

Bootstrap &lt;基础十二&gt;下拉菜单(Dropdowns)

Bootstrap 下拉菜单.下拉菜单是可切换的,是以列表格式显示链接的上下文菜单.这可以通过与 下拉菜单(Dropdown) JavaScript 插件 的互动来实现. 如需使用下列菜单,只需要在 class .dropdown 内加上下拉菜单即可.下面的实例演示了基本的下拉菜单: <!DOCTYPE html> <html> <head> <title>Bootstrap 实例 - 下拉菜单(Dropdowns)</title> <li

Jquery源码---读《uqery技术内幕,深入解析Jquery架构设计与实现原理》

前两个月项目组特别忙了,买了一本<Juqery技术内幕,深入解析Jquery架构设计与实现原理>一直放着睡大觉:进入八月份项目终于过了TR5点,算是可一个喘口气:这本书终于有时间拜读一下.下面的一两个月我将每天坚持看几页,并陆陆续续写几篇不伦不类的技术博客,谈谈自己的心得体会等等. 首先评价一下这本书吧,我本来想买<锋利的Jquery>,但是电子版翻了一下,感觉还是有点基础了:就在网上找找呀,终于看到了这本---<Juqery技术内幕,深入解析Jquery架构设计与实现原理&

Bootstrap源码分析之dropdown

源码分析: Dropdowns.scss:下拉框模块 Javascripts/bootstrap/dropdown.js:实现下拉框响应 实现功能及原理: 下拉选项卡,默认不能实现显示选中项的功能 原理: 1.利用dropdown类作为定位点,然后让子级的列表dropdown-menu绝对定位实现,还需要加一个单击点作为设置data-toggle=”dropdown”才能做关联.2. 需要js插件的支持 源码分析: 1.caret:实现向下的三角形,利用边框实现的    1.1.边框颜色默认是字

Bootstrap源码分析之nav、collapse

导航分析(nav): 源码文件:_navs.scss:导航模块Mixins/_nav-divider.scss:分隔线Mixins/_nav-vertical-align.scss:垂直对齐 1.只是用css进行了样式修饰,对Js没有任何依赖2.导航模块可以包含下拉模块3.实现了水平.垂直.水平平均分配(table-cell实现,4.0移除).tabs.胶囊等样式4.Nav-divider:有一个像素的高度实现分隔线5.Nav-stacked:垂直对齐实现6.提供了tab-content类,用于