jQuery in action 3rd - Operating on a jQuery collection

时间:2023-04-18 11:56:44

1、创建新 DOM 元素

  $('<div>Hello</div>');

  $('<img>', {
    src: 'images/little.bear.png',
    alt: 'Little Bear',
    title: 'I woof in yor general direction',
    click: function() {
      alert($(this).attr('title'));
    }

  }).appendTo('body');

2、操作 jQuery collection 对象的方法

  get([index])

    jQuery in action 3rd - Operating on a jQuery collection

    示例:$('img[alt]').get(0)

  eq(index)

    jQuery in action 3rd - Operating on a jQuery collection

    示例:$('img[alt]').eq(2)

  first()

    jQuery in action 3rd - Operating on a jQuery collection

    示例:$('img[alt]').first()

  last()

    jQuery in action 3rd - Operating on a jQuery collection

    示例:$('img[alt]').last()

  toArray()

    jQuery in action 3rd - Operating on a jQuery collection

    示例:$('img[alt]').toArray()

  index()

    jQuery in action 3rd - Operating on a jQuery collection

    示例:$(#main-menu > li').index($('#blog-link'));

  父子、祖先、子孙关系函数

    jQuery in action 3rd - Operating on a jQuery collection

  add() 

    jQuery in action 3rd - Operating on a jQuery collection

  not()

    jQuery in action 3rd - Operating on a jQuery collection

    示例,
    $('div').not(function(index) {

      // 注意,此处的 this 是一个 DOMElement 对象,而不是 jQuery 对象
      return $(this).children().length > 2;
    });

  filter()

    jQuery in action 3rd - Operating on a jQuery collection

    示例,

    $('td').filter(function() {

      // 注意,此处的 this 是一个 DOMElement 对象,而不是 jQuery 对象
      return this.innerHTML.match(/^\d+$/);
    });

    $('img').filter('[title*="dog"]').addClass('red-border');

  slice()

    jQuery in action 3rd - Operating on a jQuery collection

  has()

    jQuery in action 3rd - Operating on a jQuery collection

  map()

    jQuery in action 3rd - Operating on a jQuery collection

    示例,

    $('div').map(function() {

      // 注意,此处的 this 是一个 DOMElement 对象,而不是 jQuery 对象
      return this.id;
    });

  each()

    jQuery in action 3rd - Operating on a jQuery collection

    示例,

    $('img').each(function(index) {

      // 注意,此处的 this 是一个 DOMElement 对象,而不是 jQuery 对象
      return this.id;
    });

  is()

    jQuery in action 3rd - Operating on a jQuery collection

  end()

    jQuery in action 3rd - Operating on a jQuery collection

  addBack()

    jQuery in action 3rd - Operating on a jQuery collection