Home > Web Front-end > JS Tutorial > body text

Summarize the common methods of JQuery DOM

零下一度
Release: 2017-06-17 17:06:47
Original
1230 people have browsed it

1. Basic methods of jquery objects:

(1) get(); Get all matching elements
(2) get(index); Get one of the matching elements $(this) .get(0) is equivalent to $(this)[0]
(3) Number index(jqueryObj); Search for sub-objects
(4) each(callback); Similar to foreach, but iterates over an array of elements
For example:

$("img".each(function(index){
    this.src = "test" + index + ".jpg";
 });
Copy after login

Use return false; return true; to represent the functions of break and continue

(5) length and size(); both return the total number of elements

(6) jQuery.noConflict(true); Reset jquery default symbols
For example:

 var dom = {};
    dom.query = jQuery.noConflict(true);
Copy after login

At this time, dom.query will be used instead of $

2. JQuery selector

(1) Basic:
* Match all DOM elements
.classname Match DOM elements with the specified classname
element (DOM tag name) Match all DOM elements with the specified name

id matches the DOM element with the specified ID

, separated by, indicates matching one of the multiple selection conditions

(2) Level:
Select one [space] to select Two means all the elements in the selection one that meet the condition two
Select one[>]Select two means the first element in the selection one that meets the condition two
Select one[+]Select two means the next selection One element that matches condition 2 is next
Select one[~]Select two to indicate selecting one and then all elements that match condition 2 siblings

(3)Operator

:animated Animated element
:eq(index) Index position, such as: $("div:eq(1)"
:even Even elements
dd Odd elements
:first First
:gt(index ) All elements greater than the index
: LT (INDEX) All elements less than the index
: Header H1, H2 ... These title elements
: last last
: Not (Selector) exclude
:contains(string) The content of the selected object contains
:empty           The content of the selected object is empty  
:has(Selector)                                                                                                           using   using         using   using   using   using using   using   using   using using ’ ‐ ‐             ‐           ‐                                              .                          . child

:last-child:nth-child(index) Numbernly-child The only child element


Form

:text :checkbox :radio :image :file :submit :reset :password :button

Form status

:checked :disabled :enabled :selected

Visibility

:hidden :visible

Attributes and their operators

[Attribute name] Matches elements containing the given attribute

[att =value] Same as above

[att*=value] Fuzzy matching

[att!=value] Cannot be this value
[att$=value] Ends with this value
[att^=value ] Starts with this value
[att1][att2][att3]... Matches one of multiple attribute conditions


3. Common operations of JQuery DOM

(Refers to the common operations that can be performed after filtering the DOM through the selector, that is, the method of the JQuery object instance)

1. Attribute operations (Note: attr(name), html(), val() Yes Method that only operates on the first matching element, others operate on all)

attr(name); Get the attribute specified by the first element of the matching element

attr(key, fn), attr(key, value) sets an attribute value for all matching elements. The second parameter of the former is a function, and the value is the return value of this

function


attr(properties) uses key value Set one or more attribute values ​​for all matching elements, such as: $("img".attr({ src: "test.jpg", alt: "Test Image" });removeAttr(name) Delete the specified attribute value of the matching elementaddClass(classname) Add the class name, that is, add the class attribute
removeClass(classname)
toggleClass(classname) Switch the class name (delete if it exists, add if it does not exist)

html()
html(setvalue)
text()
text(setvalue)
val()
val(val) For ordinary elements, the usage method should be object .val (setting value); For select, radio, etc., the value is used to indicate the object to be selected, such as:
#          $("input".val(["checkvalue1", "checkvalue2"]);


2. Filtering
In fact, many filtering methods can be implemented through selector operators , so only some special operation methods are listed here.

eq(index), filter(expr), hasClass(class), is(expr), not(expr),

filter(fn)                                                                                                                                      Filter out the set of elements that match the return value of the specified function ( This function will internally calculate each object once
                  (similar to '$.each'). If the called function returns false, the element is deleted, otherwise it will be retained)

slice(start, [end]) Select a matching subset

map(callback) Convert a set of elements into other arrays (whether it is an element array or not)

andSelf() Add the selected to Current element set
end()                                                                                                                           attempts to restore the state after the previous selection was destroyed

3. Document processing : One of String, Element, jQuery, the same below.

appendTo(content) The opposite of the above, the above is to append to the selected object, this is to append the selected object to the content selection

prepend(content), prependTo(content), after(content), before(content)

replaceWith(content) Replace the selected element with content
replaceAll(selector) Replace the selected object with the current object

empty()
remove([expr])
clone()
clone(true) Clone the event together when cloning


4. CSS processing

css(name) Access the style properties of the first matching element

css(name,value) In all matching elements, set the value of a style property

css(properties) Give it a value using key-value pairs

offset() Get the displacement of the selected element, and the return value is the object Object{top,left}

height(), height(val), width(), width(val)


4.

Event processing of JQuery objects

1. Global operations

(1) ready(fn)

Events when the DOM is ready, for document The event can be abbreviated as $(function(){ … });

(2) bind(type,[data],fn) binds an event to all matching data as the additional object passed to this event function
For example:

$("p".bind("click", function(){

alert( $(this).text() );

});
function handler(event) {
alert(event.data.foo);
}
$("p".bind("click", {foo: "bar"}, handler)


(3) one(type,[data],fn) The difference above is that this event only responds once

(4) trigger(type,[data]) triggers a certain event once on each element Event

(5) triggerHandler(type,[data]) only triggers the event function, but does not trigger the same event in the browser
(6) unbind([type],[data]) deletes the bound event
(7) hover(overFn, outFn) responds to the mouse passing event
(8) toggle(fn1,fn2...) responds to the different functions each time the mouse is clicked

2. Fixed event

Without parameters, it means executing an event. With parameters, it means setting an event.


The following events can be triggered and can also be set:

blur(), change (), click(), dblclick(), error(), focus(), keydown(), keypress(), keyup(), select(), submit()


The following events It can only be set, not triggered by JS:

load(fn), mousedown(fn), mousemove(fn), mouseout(fn), mouseover(fn), mouseup(fn), resize(fn) , scroll(fn), unload(fn)


5. Effect

hide()

hide(speed,[callback]) Hide with animation, callback Function executed when the animation is completed


show()

show(speed,[callback])


toggle() Switch state

slideDown(speed,[callback]) Dynamically displays all matching elements through height changes (increasing downward), and optionally triggers a

callback function

after the display is completed. slideUp(speed,[callback]) Dynamically hides all matching elements through height changes (decreasing upwards), optionally triggering a callback function after hiding is completed.
slideToggle(speed,[callback]) Toggles the visibility of all matching elements through height changes, and optionally triggers a callback function after the switch is completed.

fadeIn(speed,[callback]) Implements the fade-in effect of all matching elements through changes in opacity, and optionally triggers a callback function after the animation is completed.
fadeOut(speed,[callback]) Realizes the fade-out effect of all matching elements through changes in opacity, and optionally triggers a callback function after the animation is completed.
fadeTo(speed,opacity,[callback]) Progressively adjusts the opacity of all matching elements to the specified opacity, and optionally triggers a callback function after the animation is completed.


animate(params,options) Function used to create custom animations.

params (Options) : 一组包含作为动画属性和终值的样式属性和及其值的集合
options (Options) : 一组包含动画选项的值的集合。

animate(params[,duration[,easing[,callback]]])

duration、 easing 是预设的动画动作
duration (String,Number) : (可选) 三种预定速度之一的字符串(“slow”, “normal”, or > “fast”或表示动画时长的毫秒数值(如:1000)
easing (String) : (可选) 要使用的擦除效果的名称(需要插件支持).> 默认jQuery提供”linear” 和 “swing”.
dequeue() 从动画队列中移除一个队列函数
queue() 返回指向第一个匹配元素的队列(将是一个函数数组)
queue(callback) 在匹配的元素的动画队列中添加一个函数
queue(queue) 将匹配元素的动画队列用新的一个队列来代替(函数数组)
stop()

六、AJAX

1、jQuery.ajax(options) 通过 HTTP 请求加载远程数据。

参数列表:
(1) async (Boolean) : (默认: true) 默认设置下,所有请求均为异步请求。如果需要发送同步请求,请将此选项设置为 false。
(2) beforeSend (Function) : 发送请求前可修改 XMLHttpRequest 对象的函数,如添加自定义 HTTP 头。XMLHttpRequest 是Function的唯一参数
(3) cache (Boolean) : (默认: true,dataType为script时默认为false) jQuery 1.2 新功能,设置为 false 将不会从浏览器缓存中加载请求信息
(4) complete (Function) : 请求完成后回调函数 (请求成功或失败时均调用)。
(5) contentType (String) : (默认: “application/x-www-form-urlencoded” 发送信息至服务器时内容编码类型。
(6) data (Object,String) : 发送到服务器的数据。将自动转换为请求字符串格式。GET 请求中将附加在 URL 后。查看 processData 选项说明以禁止此自动转换。必须为

Key/Value 格式。如果为数组,jQuery 将自动为不同值对应同一个名称。如 {foo:[“bar1″, “bar2″]} 转换为 ‘&foo=bar1&foo=bar2’。
(7) dataFilter (Function) :给Ajax返回的原始数据的进行预处理的函数。
(8) dataType (String) : 预期服务器返回的数据类型,”xml”、”html”、”script”、”json”、”jsonp”、”text”。
(9) error (Function) : (默认: 自动判断 (xml 或 html)) 请求失败时调用时间。
(10) global (Boolean) : (默认: true) 是否触发全局 AJAX 事件。设置为 false 将不会触发全局 AJAX 事件
(11) ifModified (Boolean) : (默认: false) 仅在服务器数据改变时获取新数据。使用 HTTP 包 Last-Modified 头信息判断。
(12) jsonp (String) : 在一个jsonp请求中重写回调函数的名字。
(13) password (String) : 用于响应HTTP访问认证请求的密码
(20) username (String) : 用于响应HTTP访问认证请求的用户名
(14) processData (Boolean) : (默认: true) 默认情况下,发送的数据将被转换为对象(技术上讲并非字符串) 以配合默认内容类型 “application/x-www-form-urlencoded”。如

果要发送 DOM 树信息或其它不希望转换的信息,请设置为 false。
(15) scriptCharset (String) : 只有当请求时dataType为”jsonp”或”script”,并且type是”GET”才会用于强制修改charset。通常在本地和远程的内容编码不同时使用。
(16) success (Function) : 请求成功后回调函数。参数:服务器返回数据,数据格式。 Ajax 事件。
(17) timeout (Number) : 设置请求超时时间(毫秒),此设置将覆盖全局设置。
(18) type (String) : (默认: “GET” 请求方式 (“POST” 或 “GET”), 默认为 “GET”。
(19) url (String) : (默认: 当前页地址) 发送请求的地址。

参数用 : 分开,如:

$.ajax({
url: "test.html",
cache: false,
success: function(html){
    $("#results").append(html);
}
});
Copy after login

2、封装好的简易方法(callback是成功时执行的函数,参数是返回的数据)

jQuery.get(url,[data],[callback])
jQuery.getJSON(url,[data],[callback])
jQuery.getScript(url,[callback])       载入远程JS并执行
jQuery.post(url,[data],[callback])
load(url,[data],[callback])            把远程的HTML载入当前选中的DOM中

3、事件(事件参数为event, XMLHttpRequest, ajaxOptions, thrownError)

ajaxError(callback) Execute the function when an error occurs in the AJAX request.
ajaxSend(callback) Execute the function before the AJAX request is sent
ajaxComplete(callback) Execute the function when the AJAX request is completed
ajaxStart(callback) Execute the function when the AJAX request starts
ajaxStop(callback) When the AJAX request ends Execute the function
ajaxSuccess(callback) Execute the function
jQuery.ajaxSetup(options) when the AJAX request is successful. Set the global default value of Ajax
serialize()           The content of the sequence form is a string
serializeArray()       Sequence Transform table elements (similar to '.serialize()' method) and return JSON data structure data

7. Commonly used static methods

jQuery.boxModel Whether the browser uses standard boxes in the current page Model rendering page
jQuery.browser Browser kernel identifier. Depends on navigator.userAgent.
available value: Safari Opera Msie Mozilla

jquery.Browser.Version Browser Rendering Engine Version Number.
jQuery.each(obj,callback) is a general iteration method that can be used to iterate objects and arrays.
jQuery.inArray(value,array) determines the position of the first parameter in the array (returns -1 if not found).
jQuery.map(array,callback) Converts an array-like object into an array object. The return value is data. The callback can process the old array individually.
jQuery.unique(array) Delete duplicate elements in the array.

The above is the detailed content of Summarize the common methods of JQuery DOM. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!