Syntax commonly used in js jquery 13

Ajax

Asynchronous and synchronous

使用 Ajax 最关键的地方,就是实现异步请求、接受响应及执行回调。那么异步与同步 有什么区别呢?我们普通的 Web 程序开发基本都是同步的,意为执行一段程序才能执行下 一段,类似电话中的通话,一个电话接完才能接听下个电话;而异步可以同时执行多条任务, 感觉有多条线路,类似于短信,不会因为看一条短信而停止接受另一条短信。Ajax 也可以 使用同步模式执行,但同步的模式属于阻塞模式,这样会导致多条线路执行时又必须一条一 条执行,会让 Web 页面出现假死状态,所以,一般 Ajax 大部分采用异步模式。




jQuery对Ajax采用了三层封装,其中最底层的是$.ajax(),中层封装是.load(),$.get(),$.post,最顶层是getScript和getJSON()。

2. The .load() method
jquery encapsulates Ajax a lot. For the encapsulation method, jquery uses a three-layer encapsulation, in which $.ajax() is the bottom encapsulation, and the upper encapsulation method has the .load() method,. Get ( ), .Get(),. g e t ( ) , .post() method;

.load()方法是局部方法,.load()方法中共有三个参数,一个是url,链接地址,第二个是发送的数据data,第三个是回调函数callback,期中第二个参数为非必选参数。

1. Parameter url, can provide filtering function.
$().load('data/test.html')
$().load('data/text.html .box')>>>Filter function

2. The data parameter is passed in to decide whether to submit the parameter in post mode or not is passed in as an object.
$().load('data/test.html',{ data:'admin' })

3.回调函数function(response,status,xhr){}
$().load(‘data/test.html’,{ data:‘admin’ },function(response,status,xhr){})

response :返回结果,和页面里内容一样 。

status :状态,success,或者error

xhr :XMLHttpRequest,他是一个对象

xhr has four common attributes.
Property name
Description
responseText
The text returned as the response body
responseXML
If the content type of the response body is "text/xml" or "application/xml", the XMLDOM document containing the response data will be returned.
Status
The HTTP status of the response (status code)
statusText
HTTP status instruction of

Three, .get () and .get() and. G E T ( ) and .post ()
. GET () and .get () and. g e t ( ) and .post() have four parameters. The first address parameter is a required parameter, the second parameter data is the same as the third callback function and the .load() method, and the fourth The parameter is type
$.get('data/test.html',{ name:'admin' },'html')

由于php返回的值默认为纯文本格式,所以数据格式html和text格式可以不写。如果写入数据格式,那么默认会强制转换为该格式。如果传入错误格式,那么不会有返回值。

Note: In general, the type can only be judged and does not need to be set manually. Unless the code of the entire file needs to be printed, type conversion is required.

.get () and .get() and . G E t ( ) and the difference .post () is:. Get () is submitted to get way, .get () is a way to get submitted,. G E T ( ) is to G E T way type mentioned post , .post () mode is post submission.

1.get方式提交数据是吧数据放在浏览器网址上面的,post是通过http消息,实体提交的。
2.get提交方式有大小限制,限制在2KB,而post方式不收大小限制。
3.get方式因为在浏览器中会被历史记录缓存,所以这种提交数据方式并不安全,post方式没有这种问题。
4.在服务器端(php语言),get方式通过$GET[]方式获取,post通过$POST[]方式获取。

Fourth, the $.ajax() method;

getScript()和$.getJSON();

jquery封装AJAX的最顶层,用于特定情况下的使用。 有三个参数,与$.get()和$.post()方法,前三个参数相同。

getScript()在需要资源的时候加载,是实现资源节约的时候需要用到的一个方法。
$.ajax()方法
    $.ajax({
        url:'', 链接路径
        type:'post/get'
        用什么方式提交
        data:{键:值},
        传入数据用键值对方式传入
        success:function(){ 成功是传入的参数 }
    })

Form serialization
When the form on the page needs to be submitted, if we write the data directly in the data, it will be a lot of work, so the form serialization appears.
$('form').serialize()
Form serialization is to extract the entire form content, form a key-value pair, and encode the URL.

$.ajaxSetup()  ajax初始化对于ajax可以做一个预先设置,减少重复。

$.ajaxSetup({
    url:'',
    type:'post',
    data:{user:'ddd'}
})

$.ajax({
    success:function(data){
        alert(data)
    }
})

The $.param() method is used to parse the object.

Because the browser's analysis of objects is limited, too complex objects cannot be parsed, so the $.param() method appears to parse the objects.

alert($.param({
    email:'ddd',
    user:'lll'
}))

Global function type
When is triggered

Parameters

ajaxStart
在jQuery AJAX函数或命令发起时,但在XHR实例被创建之前
类型被设置为ajaxStart的全局回调信息对象
ajaxSend
在XHR实例被创建之后,但在XHR实例被发送给服务器之前
类型被设置为ajaxSend的全局回调信息对象;XHR实例;$.ajax()函数使用的属性
ajaxSuccess
在请求已从服务器返回之后,并且响应包含成功状态码
类型被设置为ajaxSuccess的全局回调信息对象;XHR实例;$.ajax()函数使用的属性
ajaxError
在请求已从服务器返回之后,并且响应包含失败状态码
类型被设置为ajaxError的全局回调信息对象;XHR实例;$.ajax()函数使用的属性;被XHR实例返回的异常对象(如果有的话)
ajaxComplete
在请求已从服务器返回之后,并且在任何已声名的ajaxSuccess或ajaxError回调函数已被调用之后
类型被设置为ajaxComplete的全局回调信息对象;XHR实例;$.ajax()函数使用的属性
ajaxStop
在所有其他AJAX处理完成以及任何其他适用的全局回调函数已被调用之后
类型被设置为ajaxStop的全局回调信息对象

jQueryDOM
jQuery traversal:

ancestor:

parent()
parents()
parentsUntil()

Offspring:

children()---------  > 

find()---------    

brothers:

siblings()

next()

nextAll()

nextUntil()

prev()

prevAll()

prevUntil()

filter

eq()

Develop a habit, if the jQuery method can set the element value, then the method must be able to get the element value.

DOM element and attribute manipulation.

1.设置(获取)元素内容。

html()                          可以获取该元素的标签和内容

html(text) 

text(text)                     只可以获取该元素的文本内容;
 
text()
 
val(text)

val()
addClass( )方法

addClass(class) 给元素添加一个class

addClass( 'class1 class2 class3' )给元素添加多个class

removeClass(class)  给元素删除一个class

removeClass('class1 class2 class3')给元素删除多个class



toggleClass(class) 如果元素没有当前class那么添加,如果有那么删除


demo:
2. Manipulate element attributes. (Get, set, modify, delete)

.attr( ) 

.attr( )的参数有几种设置方法。

1)$('div') .attr('type')获取该属性属性值

2)$('div') .attr('type','value')设置属性值

3)$('div') .attr({
     'data':'value1',
     'data2':'value2'
})

设置一组属性值;

4)$('div').removeAttr('title');

3. Operation element style

css()

注:css()方法不仅能获取行内样式,也能获取非行内样式

css()                                       方法的参数有几种设置方法,

css(name)                               获取某个元素的行内样式


css('name',value)                    设置行内样式
 
css({
     name1:value1,
     name2:value2
})                                        设置多个行内样式

var box=$('div').css(['color','height','width']); //得到多个 CSS 样式的数组对象
 
for(var i in box){

     //逐个遍历出来 alert(i+':' +box[i]);
 
}

jquery提供了一个方法$.each()他和for in一样可以遍历对象。

$.each(obj,function(index,value){

     

})

css方法

width()

height()

innerWidth() 包含内边距(padding)

outerWidth()包含内边距和边框(     padding border)

offset()  获取某个元素相对于浏览器窗口(可视区域的距离)

position()获取某个元素相对于父元素的偏移距离

scrollTop()获取垂直滚动条的值;

scrollTop(value)设置垂直滚动条的值;

scrollLeft()获取水平滚动条的值;

scrollLeft(value)设置水平滚动条的值;

jQuery node operation

One. To create a node in order to make the page more intelligent, sometimes we want to dynamically add an element tag to the html structure page, then the first action to be done before inserting is:

1. Create a node.

var box=$('<div id="box">节点</div>'); //创建一个节点 $('body').append(box); //将节点插入到<body>元素内部

2. Insert node

append(content) 向指定元素内部后面插入节点 content

appendTo(content) 将指定元素移入到指定元素 content 内部后面

prepend(content) 向指定元素 content 内部的前面插入节点

prependTo(content) 将指定元素移入到指定元素 content 内部前面

after(content) 向指定元素的外部后面插入节点 content

before(content) 向指定元素的外部前面插入节点 content

3. Node operation

$('body').append($('div').clone(true)); //复制一个节点添加到 HTML 中

注:clone(true)参数可以为空,表示只复制元素和内容,不复制事件行为。而加上 true 参数的话,这个元素附带的事件处理行为也复制出来。

$('div').remove(); //直接删除 div 元素
$('div').empty(); //删除 div 所有的子元素

remove()方法可以接收一个参数,过滤需要删除的元素。

$('div').replaceWith('<span>节点</span>'); //将 div 替换成 span 元素

jQuery events

1.jquery event binding;

$('input').bind('click',[data],fn)

$('input').bind('click',[1,2,4,5],function(evt)  {
     alert(evt.data)
})

1)同时绑定多个事件,公用一个事件处理函数

$('input').bind('mouseover mouseout',function(){
     alert(1)
})

2) Bind multiple events at the same time, and use different event handling functions

$('input').bind({
            mouseout:function(){
                alert('移出')
            },
            mouseover:function(){
                alert('移入')
            }
 })

3) Bind different event processing functions to the same event;

$('input').bind('click',fn1)
   $('input').bind('click',fn2)

    function fn1(){
        alert(1)
    }
    function fn2(){
        alert(2)
    }

The execution order is the order of event binding.

2. Event unbinding

$('input').unbind() 不传参数的时候默认移除该DOM元素上所有事件。

$('input').unbind('mouseover') 移出该DOM元素上参数('mouseover')的事件。

3.jquery event

jquery的事件就是将JavaScript事件简写(省略了on),然后在后面加上括号。(注:前缀必须是jQuery对象)

document.onclick=function(){     > jQuery 写法>  $(document).click(function(){
     //事件处理函数                                                       //事件处理函数
 }                                                                           })

值得注意的是mouseover、mouseout 和 mouseenter、mouseleave 的差别

(mouseover)当事件发生在当前元素外的元素上的时候,会立即触发mouseout;

(mouseenter)只要事件还在当前元素内,无论是否移动到子集元素上,都不会触发mouseleave事件

(hover事件)相当于给元素同时绑定了mouseenter 和 mouseleave

         $('div').hover(fn1,fn2)   // 鼠标移入执行fn1, 鼠标移出执行fn2

        function fn1(){
            alert(1)
        }
        function fn2(){
            alert(2)
        }

4. Event Object

JavaScript事件对象是浏览器默认传入的,但是对于浏览器的兼容问题,我们需要对事件对象进行兼容。很烦!但是jQuery已经帮我们解决了所有兼容性的烦恼,并且给我们添加了很多有用的方法。

event.target                 获取绑定事件的DOM元素

event.type                    获取事件的类型

event.data                    获取事件中传递的数据

event.pageX/pageY          获取根据页面原点的X,Y值

event.screenX/screenY  获取根据显示器窗口的X,Y值

event.offsetX/offsetY     获取根据父元素X,Y值

event.which                 获取当前鼠标点击的键1,2,3

event.altKey/shiftKey/ctrlKey/   返回 true、false

5. Event bubbling (default event)

preventDefault()    //阻止默认行为   >>>>  contextmenu

stopPropagation()  //取消事件冒泡

return false  阻止默认事件和事件冒泡  双层阻止

6. Simulate events

$('input').trigger('click');

(jquery对象).trigger方法(事件名);

模拟用户触发事件:同时触发事件冒泡。

$('input').triggerHandler('click')

(jquery对象).triggerHandler方法(事件名)

模拟用户触发事件:不触发事件冒泡。

计时器自动执行事件时可用

7. The namespace of the event

$('input').bind('click',function(){
     alert(1)
})

$('input').bind('click.abc',function(){
     alert(1)
})

方便模拟事件、解绑事件时选定特定事件。

8. Event delegation

什么是事件委托:有 100 个学生同时在某天中午收到快递,但这 100 个学生不可能同时站在学校门口等,那么都会委托门卫去收取,然后再逐个交给学生。 而在 jQuery 中,我们通过事件冒泡的特性,让子元素绑定的事件冒泡到父元素(或祖先元素) 上,然后再进行相关处理即可。

传统事件绑定,会让性能变得很低,造成程序中非常多的冗余,事件委托完美解决了这个问题,他只需要给父级元素绑定一个事件,那么他的自己元素全部会在事件流中接受到事件,并对事件处理函数做出相应。

一个新的方法on(on已经全面取代了bind)

$('div').on('click','input',function(evt){

   // alert(evt.target)
        $('div').append($('input').eq(0).clone(true))

})


使用on添加事件
使用off删除on添加的事件

使用on添加的事件存在事件的命名空间,方便删除

The second parameter passed in is to change the point of this;

Transcript.html

Guess you like

Origin blog.csdn.net/qq_45555960/article/details/102868644