jQuery基础

101 阅读2分钟

官网:jquery.com
压缩版(production):code.jquery.com/jquery-3.7.…
完整版(development):code.jquery.com/jquery-3.7.…

引入jQuery

<script src="jquery-3.7.1.min.js"></script>

jQuery对象

jQuery的对象使用jQuery$作为其引用

<div id="d">hello</div>

<script>
  const d = jQuery('#d');
  const d2 = $('#d');
</script>

jQuery包装集对象

jQuery包装集对象是DOM对象的扩展

<div id="d">hello</div>

<script>
  const d = $('#d');
  console.log(d); // ce.fn.init {0: div#d, length: 1}
</script>

DOM对象转jQuery对象

<div id="d">hello</div>

<script>
  const ddom = document.getElementById('d');
  const djquery = $(ddom);
  console.log(ddom); // <div>
  console.log(djquery); // ce.fn.init {0: div#d, length: 1}
</script>

jQuery对象获取DOM对象,通过数组下标获取

<div id="d">hello</div>

<script>
  const djquery = $('#d');
  const ddom = djquery[0];
  console.log(ddom); // <div>
</script>

jQuery基础选择器

<div id="d" class="c">hello</div>

<script>
  // 元素选择器
  $('div');
  // id选择器
  $('#d');
  // 类选择器
  $('.c');
  // 通用选择器
  $('*');
  // 组合选择器
  $('selector1,selector2,...');
</script>

jQuery层次选择器

<ul>
  <li>1</li>
  <li>2</li>
</ul>
// 后代选择器
$('ul li'); // <li>1</li> <li>2</li>
// 子代选择器
$('ul>li'); // <li>1</li> <li>2</li>
// 相邻选择器
$('li+li'); // <li>2</li>
// 兄弟选择器
$('li~li'); // <li>2</li>

jQuery表单选择器

<form action="index.html?" method="get" target="_self">
  <!-- 隐藏域 -->
  <div>
    <input type="hidden" name="id" disabled>
  </div>

  <!-- 区域划分 -->
  <fieldset><legend>Main Information</legend>
    <!-- 文本框 -->
    <div>
      <label for="account">Account: </label>
      <input id="account" type="text" name="account" value="default value">
    </div>
    <!-- 密码框 -->
    <div>
      <label for="password">Password: </label>
      <input id="password" type="password" name="password">
    </div>
    <!-- 单选框 -->
    <div>
      <span>Gender: </span>
      <input type="radio" name="gender" value="male" checked>Male
      <input type="radio" name="gender" value="female">Female
    </div>
    <!-- 复选框 -->
    <div>
      <span>Hobby: </span>
      <input type="checkbox" name="hobby" value="smoking" checked>Smoking
      <input type="checkbox" name="hobby" value="drinking">Drinking
      <input type="checkbox" name="hobby" value="playing">Playing
    </div>
    
  </fieldset>
  <fieldset><legend>Other Information</legend>
    <!-- 文本域 -->
    <div>
      <span>Other: </span>
      <textarea name="other" cols="30" rows="5"></textarea>
    </div>
    <!-- 下拉选择框 -->
    <div>
      <span>Country: </span>
      <select name="country">
        <option value="ch" selected>China</option>
        <option value="en">UK</option>
      </select>
    </div>
  </fieldset>
  
  <!-- 按钮 -->
  <div>
    <!-- 提交按钮 -->
    <input type="submit" value="Confirm">
    <!-- 重置按钮-->
    <input type="reset" value="Reset">
    <!-- 普通按钮 -->
    <button type="button">Check</button>
  </div>
</form>
// :input 所有表单控件
const input = $(':input');
// :password
const password = $(':password');
// :text
const text = $(':text');
// :radio
const radio = $(':radio');
// :checkbox
const checkbox = $(':checkbox');
// :submit
const submit = $(':submit');
// :image
const image = $(':image');
// :reset
const reset = $(':reset');
// :file
const file = $(':file');
// :button
const btn = $(':button');

jQuery DOM操作

操作元素属性

<input type="checkbox" name="hobby" value="smoking" id="first" checked>Smoking
<input type="checkbox" name="hobby" value="drinking" id="second" my="val">Drinking
// 获取元素属性
// attr() 可以获取字面上定义的属性值(包括固有的、boolean类型的、自定义的)
// prop() 可以获取实际类型的属性值(包括固有的、boolean类型的)
const name = $('#first').attr('name'); // hobby
const name2 = $('#first').prop('name'); // hobby

const check = $('#first').attr('checked'); // checked
const check2 = $('#first').prop('checked'); // true

const check3 = $('#second').attr('checked'); // undefined
const check4 = $('#second').prop('checked'); // false

const my = $('#second').attr('my'); // val
const my2 = $('#second').prop('my'); // undefined
// 设置元素属性
$('#first').attr('name', 'hobbies');
$('#first').prop('name', 'hobbies');

$('#first').attr('checked', 'checked');
$('#first').prop('checked', true);

$('#second').attr('my', 'myval');
// 移除元素属性
$('#first').removeAttr('checked');
$('#second').removeAttr('my');

操作元素样式

<style>
  div {
    width: 50px;
    height: 50px
  }
  .black {
    background-color: red;
  }
  .border {
    border: 1px solid black;
  }
</style>

<div id= "d" class="black"></div>

<script>
  const s = $('#d').attr('class'); // black
  $('#d').attr('class', 'border'); // border
  $('#d').addClass('black'); // border black

  // 设置行内样式
  $('#d').css('border', '1px solid green');
  $('#d').css({'border':'1px solid green', 'font-family':'serif'});

  $('#d').removeClass('font-famliy');
</script>

操作元素内容

<div id="id">
  hello,
  <span>world</span>
  <input type="text" name="uname" value="your name">
</div>
$('#d').html() // hello,<span>world</span>
$('#d').text(); //     hello, world
$('#d>span').text('world!'); // world!

$('#d>input').val(); // your name
$('#d>input').val('my name');

元素创建/添加/删除/遍历

<style>
  #d {
    background-color: gray;
    height: 50px;
  }
</style>

<div id="d"></div>
// 创建元素
const world = $('<span>world</span>');

// 在元素内起始处添加内容(html,纯文本,DOM/jQuery对象)
$('#d').prepend(world); // world

// 将内容添加到元素内起始处
$('<span>hello</span>').prependTo($('#d')); // helloworld

// 在元素内末尾处添加内容(html,纯文本,DOM/jQuery对象)
$('#d').append('!'); // helloworld!

// 将内容添加到元素内末尾处
$('<span>?</span>').appendTo($('#d')); // helloworld!?

// 在元素前添加同级元素
$(world).before(' '); // hello world!?

// 在元素后添加同级元素
$(world).after(' '); // hello world !?
// 清空元素内容(保留标签)
$('#d').empty(); // #d { background-color: gray; height: 50px; }
// 移除元素(移除整个元素内容,包括自身的标签)
$('#d').remove();
// 遍历jQuery包装集对象,每个element是DOM对象
$('#d').each((index, element)=>{
  console.log(this); // this -> element
});

jQuery事件

ready加载事件

<script>
  // 类似与 window.onload(),等待文档加载完成后执行
  $(document).ready(()=>{
    console.log($('#d')); // ce.fn.init {0: div#d, length: 1}
  });
  
  // 简写
  $(()=>{
    console.log($('#d')); // ce.fn.init {0: div#d, length: 1}
  });
</script>

<div id="d"></div>

bind绑定事件

// $(selector).bind(eventType [, eventData], hander(eventObject))
// 绑定单个事件 $(selector).bind('eventType', fucntion(){})
$('a').bind('click', ()=>{
  alter('clicked');
});
// 绑定单个事件 $(selector).event(fucntion(){})
$('a').click(()=>{
  alter('clicked');
});

// 绑定多个事件,同一个响应函数 $(selector).bind('event1 event2 ...', fucntion(){})
$('a').bind('click mouseout', ()=>{
  alter('clicked or mouse out');
});
// 绑定多个事件,不同响应函数 $(selector).bind('event1', fucntion(){}).bind(...)
$('a').bind('click, ()=>{
  alter('clicked');
}).bind('mouseout', ()=>{
  alter('mouse out');
});
// 绑定多个事件,不同响应函数 $(selector).bind({'event1': function(){}, 'event2': function(){}})
$('a').bind({
  'click': ()=>{
    alter('clicked');
  },
  'mouseout': ()=>{
    alter('mouse out');
  },
});
// 绑定多个事件 $(selector).event1(()=>{}).event2(()=>{})
$('a').click(()=>{
  alter('clicked');
}).mouseout(()=>{
  alter('mouse out');
});

jQuery Ajax

$.ajax()

$.ajax({
  type: 'get', // 请求方法 get/post
  url: '',
  async: true, // 是否异步,默认true
  data: {...dataObj}, // 请求数据
  dataType: dataType, // 预期响应数据类型
  contentType: contentType, // 设置请求头
  success: (result)=>{}, // 请求成功回调
  error: (result)=>{}, // 请求失败回调
});
$.ajax({
    type: 'get',
    url: 'https://code.jquery.com/jquery-3.7.1.min.js',
    success: (result)=>{
        console.log(result);
    },
    error: ()=>{

    }
});

.get()/.get()/.post()

$.get(url);
$.get(url, {...dataObj});
$.get(url, function sucess(result){});
$.get(url, {...dataObj}, function sucess(result){});
$.get('https://code.jquery.com/jquery-3.7.1.min.js', {}, (result)=>{
  console.log(result);
});

$.getJSON()

只能接收JSON格式数据(JSON字符串)

$.getJSON(url);
$.getJSON(url, {...dataObj});
$.getJSON(url, function sucess(result){});
$.getJSON(url, {...dataObj}, function sucess(result){});
$.getJSON('https://code.jquery.com/jquery-3.7.1.min.js', {}, (result)=>{
  console.log(result); // 空
});