Home > Web Front-end > JS Tutorial > Learn jQuery from scratch (3) Manage jQuery packaging set_jquery

Learn jQuery from scratch (3) Manage jQuery packaging set_jquery

WBOY
Release: 2016-05-16 18:10:19
Original
803 people have browsed it
1. Summary
After using the jQuery selector to obtain the jQuery wrapper set, we need to operate it. This chapter first explains how to dynamically create elements, and then learns how to manage jQuery wrapper sets, such as adding , delete, slice, etc.


2. Introduction
There are too many APIs listed in the 2 and 3 articles of this series. I believe everyone will feel dizzy. But these are the basics. It must also be said that the foundation must be solid. In fact, you can skip these lists and look back at them or check the official API instructions when you use them later.

This chapter has very little content. It mainly explains the dynamic creation of elements and Operate various functions of the jQuery packaging set.

3. Dynamically create elements
1. Wrong programming method
We often use javascript to dynamically create elements, and there are many programmers By directly changing the HTML content of a container. For example:
Copy the code The code is as follows:


< ;html xmlns="http://www.w3.org/1999/xhtml">

Dynamic creation of objects

test layer





In the above example, I dynamically added a div element to the page by modifying the content of testDiv. But please keep in mind that this is the wrong approach!

Cause of error:

(1) The structure of the page is changed when the page is loaded. In IE6, it will appear if the network slows down or the page content is too large" Terminate operation" error. In other words, "Never change the DOM model of the page while the page is loading."

(2) Adding elements by modifying HTML content does not comply with the DOM standard. It is also encountered in actual work. After using this method to modify the content, the added elements cannot be displayed immediately in some browsers because the display engines of different browsers are different. But if we use Dom's CreateElement to create objects, in all browsers Almost everything is OK. But in jQuery, if a complete HTML string is passed in, innerHTML is also used internally. So the use of the innerHTML function is not completely negated.

So please abandon this from now on Old knowledge, use the correct method of programming introduced below.

2. Create new elements
The following introduces two correct ways to create elements.

(1) Create elements using HTML DOM
What is DOM?

With JavaScript, you can reconstruct your entire HTML document. You can add, remove, change, or rearrange items on the page.

To change something on the page, JavaScript needs access to all elements in the HTML document. This entry, along with the methods and properties for adding, moving, changing, or removing HTML elements, is obtained through the Document Object Model (DOM).

In 1998, W3C released the first level DOM specification. This specification allows access and manipulation of every individual element in an HTML page.

All browsers have implemented this standard, so DOM compatibility issues are almost impossible to find.

DOM can be used by JavaScript to read and change HTML, XHTML and XML documents.

DOM is divided into different parts (Core, XML and HTML) and levels (DOM Level 1/2/3):
Core DOM
defines a set of standards for any structured Document objects
XML DOM
defines a standard set of objects for XML documents
HTML DOM
defines a standard set of objects for HTML documents.
This article will not go into detail about using HTML DOM to create elements. Here is a simple example:
Copy the code The code is as follows :

//Create elements using Dom standards
var select = document.createElement("select");
select.options[0] = new Option("Add-in 1" , "value1");
select.options[1] = new Option("add-in2", "value2");
select.size = "2";
var object = testDiv.appendChild (select);

We can create Dom elements by using the document.createElement method, and then add them to the specified object through the appendChild method.
(2) Use the jQuery function to create elements
Created in jQuery Objects are simpler, such as creating a Div element:
$("
dynamically created div
")
We mainly use jQuery core classes A method in the library:

jQuery( html, ownerDocument )
Returns: jQuery

Dynamicly create Dom elements based on HTML original strings.

The html parameter is an HTML string. This function has been improved in jQuery 1.3.2:

When the HTML string is an element without attributes, document.createElement is used internally to create the element, for example:

Copy code The code is as follows:

//jQuery internally uses document.createElement to create elements:
$("
").css("border","solid 1px #FF0000" ).html("Dynamicly created div").appendTo(testDiv);

Otherwise, use the innerHTML method to create elements:
Copy code The code is as follows:

//jQuery internally uses innerHTML to create elements:
$("
").appendTo(testDiv);

3. Add elements to the object
We can use the above two methods Create an element, but as mentioned above, you must not change the DOM structure of the page when the page is loaded, such as adding an element. The correct approach is to add or delete elements after the page is loaded.
Traditionally, use window .onload accomplishes the above purpose:
Copy code The code is as follows:

//After DOM is loaded Add element
//Traditional method
window.onload = function() { testDiv.innerHTML = "
Dynamicly created div
"; }

Although it is possible to add new elements after the DOM is completely loaded, unfortunately, the browser executes the window.onload function not only after the DOM tree is built, but also after all images and After other external resources are completely loaded and displayed in the browser window. So if a certain image or other resource takes a long time to load, the visitor will see an incomplete page, or even execute the required dependencies before the image is loaded. Scripts for dynamically added elements can cause script errors.

The solution is to wait for the DOM to be parsed and execute our function before images and external resources are loaded. Making this possible in jQuery:
Copy code The code is as follows:

//jQuery uses dynamically created $(document).ready (function) method
$(document).ready(
function() { testDiv.innerHTML = "
Use dynamically created $(document). ready(function) method
"; }
);

Or use simple syntax:
Copy code The code is as follows:

//jQuery uses the $(function) method
$(
function() { testDiv.innerHTML = "
Use $(function) method
"; }
);

使用$()将我们的函数包装起来即可. 而且可以在一个页面绑定多个函数, 如果使用传统的window.onload则只能调用一个函数.

所以请大家将修改DOM的函数使用此方法调用. 另外还要注意document.createElement和innerHTML的区别. 如果可以请尽量使用document.createElement和$("
")的形式创建对象.
四.管理jQuery包装集元素
既然学会了动态创建元素, 接下来就会想要把这些元素放入我们的jQuery包装集中.

我们可以在jQuery包装集上调用下面这些函数, 用来改变我们的原始jQuery包装集, 并且大部分返回的都是过滤后的jQuery包装集.

jQuery提供了一系列的函数用来管理包装集:

1.过滤 Filtering

名称 说明 举例
eq( index ) 获取第N个元素 获取匹配的第二个元素:
$("p").eq(1)
filter( expr )

筛选出与指定表达式匹配的元素集合。

保留带有select类的元素:
$("p").filter(".selected")
filter( fn )

筛选出与指定函数返回值匹配的元素集合

这个函数内部将对每个对象计算一次 (正如 '$.each'). 如果调用的函数返回false则这个元素被删除,否则就会保留。

保留子元素中不含有ol的元素:

$("div").filter(function(index) {
  return $("ol", this).size() == 0;
});

is( expr )

注意: 这个函数返回的不是jQuery包装集而是Boolean值

用一个表达式来检查当前选择的元素集合,如果其中至少有一个元素符合这个给定的表达式就返回true。

如果没有元素符合,或者表达式无效,都返回'false'. 'filter' 内部实际也是在调用这个函数,所以,filter()函数原有的规则在这里也适用。

由于input元素的父元素是一个表单元素,所以返回true:
$("input[type='checkbox']").parent().is("form")
map( callback )

将一组元素转换成其他数组(不论是否是元素数组)

你可以用这个函数来建立一个列表,不论是值、属性还是CSS样式,或者其他特别形式。这都可以用'$.map()'来方便的建立

把form中的每个input元素的值建立一个列表:

$("p").append( $("input").map(function(){
  return $(this).val();
}).get().join(", ") );

not( expr ) 删除与指定表达式匹配的元素 从p元素中删除带有 select 的ID的元素:
$("p").not( $("#selected")[0] )

slice( start, end )

选取一个匹配的子集 选择第一个p元素:
$("p").slice(0, 1);

2.查找 Finding

名称 说明 举例
add( expr )

把与表达式匹配的元素添加到jQuery对象中。这个函数可以用于连接分别与两个表达式匹配的元素结果集。

动态生成一个元素并添加至匹配的元素中:
$("p").add("Again")
children( [expr] )

取得一个包含匹配的元素集合中每一个元素的所有子元素的元素集合。

可以通过可选的表达式来过滤所匹配的子元素。注意:parents()将查找所有祖辈元素,而children()只考虑子元素而不考虑所有后代元素。

查找DIV中的每个子元素:
$("div").children()
closest( [expr] ) 取得与表达式匹配的最新的父元素

为事件源最近的父类li对象更换样式:

$(document).bind("click", function (e) {
  $(e.target).closest("li").toggleClass("hilight");
});

contents( ) 查找匹配元素内部所有的子节点(包括文本节点)。如果元素是一个iframe,则查找文档内容 查找所有文本节点并加粗:
$("p").contents().not("[nodeType=1]").wrap("");
find( expr )

搜索所有与指定表达式匹配的元素。这个函数是找出正在处理的元素的后代元素的好方法。

所有搜索都依靠jQuery表达式来完成。这个表达式可以使用CSS1-3的选择器语法来写。

从所有的段落开始,进一步搜索下面的span元素。与$("p span")相同:
$("p").find("span")
next( [expr] )

取得一个包含匹配的元素集合中每一个元素紧邻的后面同辈元素的元素集合。

这个函数只返回后面那个紧邻的同辈元素,而不是后面所有的同辈元素(可以使用nextAll)。可以用一个可选的表达式进行筛选。

找到每个段落的后面紧邻的同辈元素:
$("p").next()
nextAll( [expr] )

查找当前元素之后所有的同辈元素。

可以用表达式过滤

给第一个div之后的所有元素加个类:
$("div:first").nextAll().addClass("after");
offsetParent( ) 返回第一个有定位的父类(比如(relative或absolute)).
 
parent( [expr] )

取得一个包含着所有匹配元素的唯一父元素的元素集合。

你可以使用可选的表达式来筛选。

查找每个段落的父元素:
$("p").parent()
parents( [expr] ) 取得一个包含着所有匹配元素的祖先元素的元素集合(不包含根元素)。可以通过一个可选的表达式进行筛选。 找到每个span元素的所有祖先元素:
$("span").parents()
prev( [expr] )

取得一个包含匹配的元素集合中每一个元素紧邻的前一个同辈元素的元素集合。

可以用一个可选的表达式进行筛选。只有紧邻的同辈元素会被匹配到,而不是前面所有的同辈元素。

각 단락의 바로 앞에 있는 형제 요소 찾기:
$("p").prev()
prevAll( [expr] )

현재 요소 이전의 모든 형제 요소 찾기

표현식을 사용하여 필터링할 수 있습니다.

마지막 div 이전의 모든 div에 클래스 추가:
$("div:last").prevAll().addClass("before");
남매( [expr] ) 일치하는 요소 세트에 있는 각 요소의 모든 고유 형제를 포함하는 요소 세트를 가져옵니다. 선택적 표현식으로 필터링할 수 있습니다. 각 div의 모든 형제 찾기:
$("div").siblings()

3. 체인 연결

名称 说明 举例
andSelf( )

加入先前所选的加入当前元素中

对于筛选或查找后的元素,要加入先前所选元素时将会很有用。

选取所有div以及内部的p,并加上border类:
$("div").find("p").andSelf().addClass("border");
end( ) 回到最近的一个"破坏性"操作之前。即,将匹配的元素列表变为前一次的状态。

如果之前没有破坏性操作,则返回一个空集。所谓的"破坏性"就是指任何改变所匹配的jQuery元素的操作。这包括在 Traversing 中任何返回一个jQuery对象的函数--'add', 'andSelf', 'children', 'filter', 'find', 'map', 'next', 'nextAll', 'not', 'parent', 'parents', 'prev', 'prevAll', 'siblings' and 'slice'--再加上 Manipulation 中的 'clone'。
选取所有的p元素,查找并选取span子元素,然后再回过来选取p元素:

$("p").find("span").end()
이름

설명




andSelf( ) 이전에 선택한 요소를 현재 요소에 추가 필터링되거나 검색된 요소에 이전에 선택한 요소를 추가하고 싶을 때 유용합니다. 모든 div와 내부 p를 선택하고 테두리 클래스를 추가합니다: $("div").find("p").andSelf().addClass("border") ; 끝( ) 마지막 "파괴적인" 작업으로 돌아갑니다. 즉, 일치하는 요소 목록을 이전 상태로 변경합니다. 이전에 파괴적인 작업이 없었다면 빈 세트가 반환됩니다. 소위 "파괴적"은 일치하는 jQuery 요소를 변경하는 모든 작업을 의미합니다. 여기에는 jQuery 객체('add', 'andSelf', 'children', 'filter', 'find', 'map', 'next', 'nextAll', 'not', 'parent)를 반환하는 Traversing의 모든 함수가 포함됩니다. ', 'parents', 'prev', 'prevAll', 'siblings' 및 'slice' - 조작의 'clone' 추가. 모든 p 요소를 선택하고, 범위 하위 요소를 찾아 선택한 다음, 돌아가서 p 요소를 선택합니다. $("p").find("span" ).end()5. 자주 사용하는 함수 예시[계속] 6. 이 기사의 내용은 상대적으로 적고, 주로 요소를 동적으로 생성하고 jQuery 패키징 세트를 관리하는 방법을 설명합니다. 인터페이스 문서에는 예제가 너무 많아서 아직 예제를 작성할 시간이 없었습니다. 내일 출근하세요. 양해 부탁드리며 나중에 시간이 나면 보충하겠습니다. 저자: Zhang Ziqiu출처: http://www.cnblogs.com/zhangziqiu/
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