jQuery 基础

105 阅读2分钟

jQuery简介

jQuery是一套跨浏览器的JavaScript库,用于简化JavaScriptHTML之间的操作。其设计的宗旨是**“write Less,Do More”**,即倡导写更少的代码,做更多的事情。

jQuery基本的用法,就是 选择某个网页元素,然后对其进行一些操作。

本文主要介绍的基本功能点如下

1. 选中网页元素

将一个表达式,放入jQuery函数(简写$)中,然后得到被选中的元素

表达式可以是CSS选择器

$(selector)

也可以是jQuery特有的表达式

$('a:first') //选择网页中第一个a元素

$('tr:odd') //选择表格的奇数行

$('#myForm :input') // 选择表单中的input元素

2. 创建元素

只需要把新元素直接传入jQuery()

$(fragment)

实现方法大概是接收到标签后,生成一个template元素,然后将待创建的元素插入到template作为子元素,并将其返回,这样就可以将片段转变为node节点

function createElement(string) {
    const container = document.createElement("template");
    container.innerHTML = string.trim();
    return container.content.firstChild;
  }

3. 关于链式操作

链式操作实现原理,主要是在调用jQuery对象的方法后将对象返回,被返回的对象有各种api方法,所以可以继续调用,下面是一个简易的实现

window.jQuery = function (selectorOrArray) {
    let elements;
    if (typeof selectorOrArray === 'string') {
        elements = document.querySelectorAll(selectorOrArray);
    } else if (selectorOrArray instanceof Array) {
        elements = selectorOrArray
    }
    const api = Object.create(jQuery.prototype)
    Object.assign(api, {
        elements: elements,
        oldApi: selectorOrArray.oldApi
    })
    return api
};
jQuery.fn = jQuery.prototype = {
    each(fn) {
        for (let i = 0; i < this.elements.length; i++) {
            fn(this.elements[i], i)
        }
    },
    addClass(string) {
        this.each((node) => {
            node.classList.add(string)
        })
        return this; //只有返回api才可以继续链式调用
    },
    find(selector) {
        let array = []
        this.each((node) => {
            array = array.concat(Array.from(node.querySelectorAll(selector)))
            // 或者使用下面的写法
            // array = array.push(...node.querySelectorAll(selector)) 
        })
        array.oldApi = this
        return jQuery(array) //既要返回api,又要返回array
    },
    print() {
        console.log(this.elements)
    },

    // 返回上一次操作的elements
    end() {
        return this.oldApi
    },
    parent() {
        let array = [];
        this.each((node) => {
            if (array.indexOf(node.parentNode) === -1) {
                array.push(node.parentNode)
            }
        })
        array.oldApi = this
        return jQuery(array)
    },
    children() {
        let array = [];
        this.each((node) => {
            array.push(...node.children)
        })
        array.oldApi = this
        return jQuery(array)
    },
    siblings() {
        let array = [];
        this.each((node) => {
            let arr = Array.from(node.parentNode.children).filter((i) => {
                return i !== node
            })
            array.push(...arr)
        })
        array.oldApi = this
        return jQuery(array)
    },
    get(index) {
        return this.elements[index]
    }
}

4. 移动元素

  • 内部插入:appendappendToprependprependTo
<p> hello </p>

let span = $('<span>world</span>').get(0)
$('p').get(0).append(span)  //<p> hello<span>world</span> </p>


let span = $('<span>world</span>')
span.appendTo($('p').get(0))  //<p> hello<span>world</span> </p>

let span = $('<span>world</span>').get(0)
$('p').get(0).prepend(span)  //<p> <span>world</span>hello </p>

let span = $('<span>world</span>')
span.prependTo($('p').get(0))  //<p> <span>world</span>hello </p>

  • 外部插入 afterbeforeinsertAfterinsertBefore
<p class='first'>hello</p>
<p class='third'>world</p>

$('.third').get(0).before($('<span>insert before<span>').get(0))  // A插B前
$('.third').get(0).after($('<span>insert after<span>').get(0))   // A插B后

$('<span>insert Before</span>').insertBefore( $('.third').get(0)) // B插A前
$('<span>insert After</span>').insertAfter( $('.third').get(0))   // B插A后
  • 包裹 wrapunwrapwrapAllwrapInner
<p class='first'>hello</p>
<div class='second'>test</div>
<p class='third'>world</p>


$('p').wrap('<div></div>')

// 对所有p加一层div包裹住
<div><p class="first">hello</p></div>
<div class="second">test</div>
<div><p class="third">world</p></div>
  • 替换 replaceWithreplaceAll
<p class='first'>hello</p>
<div class='second'>test</div>
<p class='third'>world</p>

$('.first').replaceWith($('.third')) // 将third移动到first,不是复制

<p class="third">world</p>
<div class="second">test</div>
  • 删除 empty、remove、detach
<p class='first'>hello</p>
<p class='third'>world</p>

$('p').wrapAll('<div></div>')
$('div').empty()
//dom中删除了所有p元素 只剩下  <div></div>
  • 复制 clone

5. 修改元素的属性

.html()取出或设置html内容

.text()取出或设置text内容

.attr() 取出或设置某个属性的值

jQuery在同一个方法中,通过判断参数的个数,实现获取(getter)或改写(setter),上述几个方法有采用此思想

还有其他的特性,后续有机会再补充

本文只列举部分api,详细的文档请见jQuery中文文档