JavaScript jQuery(七)

2017-11-30  本文已影响0人  EmileSu_大苏

jQuery 提供了快速和便捷的方法来实现 JS 任务, 并保持主流浏览器的兼容性

  1. 选择元素
    通过 CSS 样式选择器来获取元素
  2. 高效开发
    通过一行代码来完成 DOM 的系列任务
  3. 处理事件
    直接在元素上附加事件监听器

创建 jQuery 对象函数, 函数中的参数就是 CSS 样式选择器.
$( ' li.hot ' )

使用jQuery 方法来操作元素
$( ' li.hot ' ).addClass( ' complete ' );


循环

当 jQuery 返回多个元素时,使用 class 属性来实现循环

$('li em').addClass('seasonal');    //选择元素
$('li.hot').addClass('favorite');    //选择样式

链式操作

在同一个选取结果上使用多个 jQuery 方法

$('li[id!="one"]').hide().delay(500).fadeIn(1400);    //同时使用隐藏元素/穿件暂停/淡入元素三个方法

获取元素内容

.html()
返回标签+内容

.text()
只会返回文本内容


更新元素内容

.html()
更新 html 内容

.text()
更新文本内容

$(function() {
  $('li:contains("pine")').text('almonds');
  $('li.hot').html(function() {
    return '<em>' + $(this).text() + '</em>';
  });
  $('li#one').remove();
});

.replaceWith()
替换元素中的内容

.remove()
移除内容


插入元素

.before()
将内容插入到元素之前

.after()
将内容插入到元素之后

.prepend()
将内容插入到元素内部, 紧跟在开始标签之后

.append()
将内容插入到元素内部,紧跟在结束标签之前

$(function() {
  $('ul').before('<p class="notice">Just updated</p>');
  $('li.hot').prepend('+ ');
  var $newListItem = $('<li><em>gluten-free</em> soy sauce</li>');
  $('li:last').after($newListItem);
});

获取和设置属性值

.sttr()
获取或设置属性
$(' li#one ').attr(' id '); //读取属性时小括号中指定属性名称
$(' li#one ').attr(' id ', ' hot '); //更新属性时, 需要同时指定属性名称和属性值

.removeAttr()
移除属性(及其属性值)
$(' li#one ').removeAttr(' id ');

.addClass()
向 class 属性中添加一个新的值

.removeClass()
从 class 属性中移除一个属性值

$(function() {
  $('li#three').removeClass('hot');
  $('li.hot').addClass('favorite');
  $('ul').attr('id', 'group');
});

获取和设置 CSS 属性值

.css()
获取或设置 CSS 属性的值
var backgroundColor = $('li').css('background-color'); //获取CSS 属性时, 需要在小括号指定获取哪个属性
$('li').css('background-color', '#666'); //设置 CSS 属性值时, 需要在小括号指定参数, 即属性名称和对应值

设置多个属性值时, 使用花括号

$('li').css({
   'background-color': '#666',
   'font-family': 'Courier'
});
//例:
$(function() {
  var backgroundColor = $('li').css('background-color');
  $('ul').append('<p>Color was: ' + backgroundColor + '</p>');
  $('li').css({
    'background-color': '#c5a996',
    'border': '1px solid #fff',
    'color': '#000',
    'text-shadow': 'none',
    'font-family': 'Georgia',
    'padding-left': '+=75'
  });
});

.each() 方法遍历

.each() 方法的参数是一个函数

this 关键字可以用来访问当前元素
$(this) 的写法是用 this 关键字创建一个包含当前元素的 jQuery 对象

$('li').each(function(){
  var ids = this.id;
  $(this).append(' <em class="order" ' + ids + '</em>' >);
});

.on() 事件方法

.on() 方法需要两个参数:

  1. 第一个参数是需要响应的事件
  2. 第二个参数是发生事件需要运行的代码函数
$('li').on('click', function() {
  $(this).addClass('complete');
});
事件对象

将事件对象作为命名参数e, 并在函数中使用这个名称来指代事件对象, 即可访问其属性和方法 .

$(function() {

  $('li').on('click', function(e) {
    $('li span').remove();
    var date = new Date();
    date.setTime(e.timeStamp);
    var clicked = date.toDateString();
    $(this).append('<span class="date">' + clicked + ' ' + e.type + '</span>');
  });

});
事件处理程序中的其他参数
  1. 第一个参数是需要响应的事件( 可以响应多个事件 )
  2. 第二个参数可以作为选择器来赛选后代节点
  3. 第三个参数可向触发事件, 传递额外额信息
$(function() {
  var listItem, itemStatus, eventType;

  $('ul').on(
    'click mouseover',        //这里响应了两个事件
    ':not(#four)',          //对响应事件的元素进行筛选,去除 id 为 four 的元素
    {status: 'important'},        //向事件传递额外信息
    function(e) {
      listItem = 'Item: ' + e.target.textContent + '<br />';
      itemStatus = 'Status: ' + e.data.status + '<br />';
      eventType = 'Event: ' + e.type;
      $('#notes').html(listItem + itemStatus + eventType);
    }
  );

});

遍历 DOM

根据当前选取结果来选择不通关系的其他元素
$(function() {
  var $h2 = $('h2');
  $('ul').hide();
  $h2.append('<a> show </1>');

  $h2.on('click', function() {
    $h2.next()                      //当前元素的下一个兄弟节点
      .fadeIn(500)
      .children('.hot')             //当前元素的所有 class 为 hot 的子节点
      .addClass('complete');        
    $h2.find('a').fadeOut();        //find()方法选取当前选取结果内符合的所有元素
  });
});
在选取结果中添加或筛选元素
$(function() {
  var $listItems = $('li');

  $listItems.filter('.hot:last').removeClass('hot');        //filter()方法在匹配结果中查找符合第二个选择器的元素
  $('li:not(.hot)').addClass('cool');        //.not()/:not() 方法查找不匹配这个选择器的元素
  $listItems.has('em').addClass('complete');        //.has()/:has()方法在匹配集中找后代节点中符合选择器的元素

  $listItems.each(function() {
    var $this = $(this);
    if ($this.is('.hot')) {        //.is 查找当前选择结果中是否有满足的条件, 并返回布尔值(用于做判断)
      $this.prepend('Priority item: ');
    }
  });

  $('li:contains("honey")').append(' (local)');        //:contains()方法选择包含自定文字的元素
});

---
//对应的 HTML 演示:
<body>
  <div id="page">
    <h1 id="header">List</h1>
    <h2>Buy groceries</h2>
    <ul>
      <li id="one" class="hot"><em>fresh</em> figs</li>
      <li id="two" class="hot">pine nuts</li>
      <li id="three" class="hot">honey</li>
      <li id="four">balsamic vinegar</li>
    </ul>
  </div>
  <script src="js/jquery-1.11.0.js"></script>
  <script src="js/filters.js"></script>
</body>
按索引编号查找元素

jQuery 对象可以当做类似数组的对象来使用

方法/选择器
.eq() 匹配索引编号的元素
:lt() 索引编号小鱼指定数字的元素
:gt() 索引编号大于指定数字的元素

$(function() {
  $('li:lt(2)').removeClass('hot');
  $('li').eq(0).addClass('complete');
  $('li:gt(2)').addClass('cool');
});

选取表单元素

添加新列表示例:
$(function() {

  var $newItemButton = $('#newItemButton');
  var $newItemForm = $('#newItemForm');
  var $textInput = $('input:text');

  $newItemButton.show();
  $newItemForm.hide();

  $('#showForm').on('click', function(){
    $newItemButton.hide();
    $newItemForm.show();
  });

  $newItemForm.on('submit', function(e){      //.on 创建表单提交事件
    e.preventDefault();        //使用.preventDefault()方法来阻止表单提交到服务器
    var newText = $textInput.val();        //使用. val() 方法来捕获用户输入的信息
    $('li:last').after('<li>' + newText + '</li>');
    $newItemForm.hide();
    $newItemButton.show();
    $textInput.val('');
  });

});

剪切和复制元素

剪切

.remove() 移除匹配的元素及其后代
.detach() 剪切, 会在内存中保存副本
.empty() 移除匹配元素的子节点及后代节点
.unwrap() 移除匹配元素的父节点, 并保留匹配元素

复制

.clone() 创建匹配元素及其后代几点的副本

$(function() {
  var $p = $('p');
  var $clonedQuote = $p.clone();      //.clone()方法复制并保存在变量中
  $p.remove();        //这里被移除, 但是顺便已经被复制过 
  $clonedQuote.innerAfter('h2');

  var $moveItem = $('#one').detach();        //.detach() 方法剪切, 实际上类似于复制并删除
  $moveItem.appendTo('ul');
});

全章节示例:
一个任务处理程序,用能:
1.用户可以添加新的列表项
2.用户点击一个列表项来表示它已经完成, 同时该列表项会移到列表的最后, 并标记为完成.
3.当一个列表项被标记为完成并在此点击它时, 就会将其从列表中删除
4.列表项的数目会在列表上方的标题中实时进行更新.

$(function() {

  // SETUP
  var $list, $newItemForm, $newItemButton;
  var item = '';                                 // item is an empty string
  $list = $('ul');                               // Cache the unordered list
  $newItemForm = $('#newItemForm');              // Cache form to add new items
  $newItemButton = $('#newItemButton');          // Cache button to show form

  $('li').hide().each(function(index) {          // Hide list items
    $(this).delay(450 * index).fadeIn(1600);     // Then fade them in
  });

  // ITEM COUNTER
  function updateCount() {                       // Create function to update counter
    var items = $('li[class!=complete]').length; // Number of items in list
    $('#counter').text(items);                   // Added into counter circle
  }
  updateCount();                                 // Call the function

  // SETUP FORM FOR NEW ITEMS
  $newItemButton.show();                         // Show the button
  $newItemForm.hide();                           // Hide the form
  $('#showForm').on('click', function() {        // When click on add item button
    $newItemButton.hide();                       // Hide the button
    $newItemForm.show();                         // Show the form
  });

  // ADDING A NEW LIST ITEM
  $newItemForm.on('submit', function(e) {       // When a new item is submitted
    e.preventDefault();                         // Prevent form being submitted
    var text = $('input:text').val();           // Get value of text input
    $list.append('<li>' + text + '</li>');      // Add item to end of the list
    $('input:text').val('');                    // Empty the text input
    updateCount();                              // Update the count
  });

  // CLICK HANDLING - USES DELEGATION ON <ul> ELEMENT
  $list.on('click', 'li', function() {
    var $this = $(this);               // Cache the element in a jQuery object
    var complete = $this.hasClass('complete');  // Is item complete

    if (complete === true) {           // Check if item is complete
      $this.animate({                  // If so, animate opacity + padding
        opacity: 0.0,
        paddingLeft: '+=180'
      }, 500, 'swing', function() {    // Use callback when animation completes
        $this.remove();                // Then completely remove this item
      });
    } else {                           // Otherwise indicate it is complete
      item = $this.text();             // Get the text from the list item
      $this.remove();                  // Remove the list item
      $list                            // Add back to end of list as complete
        .append('<li class=\"complete\">' + item + '</li>')
        .hide().fadeIn(300);           // Hide it so it can be faded in
      updateCount();                   // Update the counter
    }                                  // End of else option
  });                                  // End of event handler

});
上一篇下一篇

猜你喜欢

热点阅读