jQuery 基础

jQuery 基础

jQuery的介绍
  • 库: 小而精

    框架: 大而全

    核心:write less do more

jQuery 入口函数

//入口函数 返回的是jquery对象
$(document).ready(function(){
    // 文档加载 时
    alert(1);
});
$(window).ready(function(){
    // 窗口加载
    alert(2);
});

$(function(){
    // 默认  document
    alert(1);
});
// 自执行函数
(function () {
    alert(11111)
})();
console.log($);
console.log(jQuery);
console.log($('div'));

选择器

基本选择器

  • id选择器
  • 类选择器
  • 标签选择器
  • 子代
  • 后代
  • 组合
  • 交集
  • 通配符
  • 兄弟 + ~

基本过滤选择器 + 属性选择器

$('li:eq(index)')   //  获取一个标签
$('li:gt(index)')   // 大于 index 的 元素
li:lt(index)   // 小于 index 的元素
li:odd   // 奇数
li:even   // 偶数
li:first  //  第一个
li:last   // 最后一个

// 属性选择器
input[type='text']

筛选的方法***

jQuery和js对象相互转换**

//js==>jquery
$(js对象)
jquery对象 => js对象
$('li')[index];
$('li').get(index);

样式设置

// 两个参数为设置值
$('#box').css("color", "red")
// 一个参数为获取值
$('#box').css("color")
  • jquery的选择器(获取DOM对象 注意 它获取的是jQuery对象,而不是jsDOM对象) 标签选择器
// 选择器
$(function () {

    $("div")[0].style.backgroundColor = "red";
    var op  = $("p");
    console.log(op);
    var acti = $();

    op.click(function () {
        // 点击的对象为  DOM js 对象  需转换为 jQuery 对象  $(this)

        console.log(this.innerText);   // 获取对象的值
        console.log($(this).text());   // 获取对象的值

        // 替换对象的值
        // $(this).text("11111111111")

        // 返回一个 jQuery 对象
        console.log($(this).text("1111111"))
    })
})

筛选选择器

// 查找的是后代  (子子孙孙)
console.log( $('ul').find('a'));
//查找的是亲儿子 如果指定亲儿子,就在children('选择器'),想获取所有的亲儿子 不用写参数
console.log( $('ul').children());
//查找的只有亲爸
console.log( $('a').parent());
//$(`li:eq(${index})`)
console.log( $('ul li').eq());
// 选取兄弟元素 除了自己
console.log( $('span').siblings());

siblings

//获取索引
let i = $(this).index()
//返回了jquery对象
//链式编程
$(this).css('backgroundColor','red').siblings('button').css('backgroundColor','#666');
$('div').eq(i).addClass('active').siblings('div').removeClass('active');
 $('ul li').click(function () {
$(this).find('a').css('color','red').parent().siblings('li').find('a').css('color','blue');
        })

对标签属性的操作

attr()  // 同 .css()  单个参数表示查询该属性    两个参数表示 设置该属性
removeattr()  // 移除属性 可移除多个 用空格 分开

对象属性操作

prop() // 
removeprop()  // 单个移除属性

类的操作

addclass()  // 设置类名  可设置多个
removeclass()  // 移除类名  不会影响之前的 类名
taggleckass()  // 单个操作  添加 和移除 

值的操作

text()  // 设置文本  innerText()
html()  // 设置文本及标签  innerHtml()
val()  // 设置 value 值

文档的操作

// 后置插入
$(".div").append(子标签);   子标签.appendTo(父标签);
// 前置插入
$(".div").prepend(字标签);   子标签.propenTo(父标签);

// 兄弟插入 后插入
目标兄弟.after(要插入的兄弟标签)  要插入的兄弟标签.inertAfter(目标兄弟)
// 兄弟插入 前插入
目标兄弟.before(要插入的兄弟)   要插入的兄弟.inertBefore(目标兄弟)

// 删除
$('seletor').remove();  // 删除整个标签  事件也删除
$('seletor').detach();  // 删除整个标签  保留事件

// 清空
$('seletor').empty();  // 清空
$('seletor').html('');  // 清空
$('seletor').text("");  // 清空

// 替换
$('seletor').replacewith();  
$('seletor').replaceall();  

posted @ 2019-05-01 18:56  拐弯  阅读(248)  评论(0编辑  收藏  举报