Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

jQuery 基础知识 #10

Open
eyasliu opened this issue Jun 12, 2016 · 0 comments
Open

jQuery 基础知识 #10

eyasliu opened this issue Jun 12, 2016 · 0 comments
Labels

Comments

@eyasliu
Copy link
Owner

eyasliu commented Jun 12, 2016

jQuery && $

在jquery中, $ 变量是 jQuery 变量的简写

jQuery === $  // true

$ 方法

  • $ 方法接收一个包含 CSS 选择器的字符串,然后用这个字符串去匹配一组元素
  • $ 方法接收原始 HTML 标记字符串,动态创建由 jQuery 对象包装的 DOM 元素。同时设置一系列的属性、事件等
  • $ 方法接收一个函数作为参数,绑定一个在DOM文档载入完成后执行的函数。$(document).ready()的简写

事件

事件的触发会有三个阶段,捕获,处于目标,冒泡

  • 捕获:事件由最上层元素接收,然后逐步向更具体的元素传播
  • 处于目标:在最具体的元素中触发
  • 冒泡:事件开始时,由最具体的元素接收,然后逐步向上传播

捕获阶段不会触发事件,事件会在处于目标阶段开始,逐渐冒泡触发

事件绑定

// 使用通用事件名作为函数
$('button').click(function(event){
  // event 为事件对象
})

// 使用 bind 或者on
$('button').bind('click', function(event){})
$('button').on('click', function(event){})

// 使用 on 事件委托
$('body').on('click', 'button', function(event){})

阻止冒泡

事件处理函数有一参数 event,在该函数中调用event.stopPropagation() 可阻止事件冒泡

$('button').click(function(event){
  event.stopPropagation()
})

扩展

$.fn是指jquery的命名空间,加上fn上的方法及属性,会对jquery实例每一个有效。

扩展为了不污染全局变量,应使用立即执行函数包裹

(function($, document, window){
  $.fn.myExtention = function(){
    // extendsion code
    // ...
  }
})(jQuery, document, window)
@eyasliu eyasliu added the 前端 label Jun 12, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant