jquery总结

选择器###

一般选择

  • var element = $('#id')/$('.class')/$('TagName');

符合选择器

  • var element = $('.bar .foo')/$('input[name="username"]')/$('.class:first');

DOM遍历###

  • 查找匹配子节点 node.find('.test')

  • 选择父节点 node.parent()

  • 查找一组父节点 node.parents(".option")

  • 选择直接子元素 node.children()

  • 通过索引查找 node.eq(o)

  • 返回第一个元素 node.first()

  • 过滤查找

node.filter(function(){
 return $(this).hasClass('.foo');
})
  • 使用迭代器
node.map(fuction(elem, index){});

node.each(function(index, elem){});
  • 添加元素 node.add($('p'))

DOM操作###

  • 添加新元素
node.append($('<div/>'));
node.prepend($('<hr/>'));
node.after($('<p/>'));
node.before($('<p/>'));
  • 删除元素 node.remove()

  • CLASS相关

node.addClass('class');
node.removeClass('class');
node.toggleClass('class');
node.hasClass('class');

  • 内容
node.text();
node.text('text');
node.html();
node.html('<p>hi</p>');
node.empty();

事件###

事件中主要要注意回调函数的this

  • 使用self

  • 使用 node.click($.proxy(function(){},this));

扩展###

  • 添加类函数,直接在jquery对象上创建函数
jQuery.myExt = function(){};
$.myExt();
  • 添加函数实例,并且在元素选择器上有效,只要在jQuery.fn对象上创建函数即可,它其实就是 jQuery.prototype的别名;最佳实践是在扩展的最后返回当前上下文,这样就能用链式
jQuery.fn.myExt = function(){
  $(this).html('bar');
  return this;
}
  • 将扩展用模块的模式来封装,这可以避免作用域泄漏和变量冲突
(function($){
  var replaceLinks = function(){
    var re = /(http|https|ftp):/[w?&./;#~%"=-]*>))/g;
    $(this).html($(this).html().replace(re, '<a target="_blank" href="$1">$1<a/>'));
  };
  $.fn.autolink = function() {
    return this.each(replaceLinks);
  };
})(jQuery);
原文地址:https://www.cnblogs.com/jinkspeng/p/4294395.html