Home > Web Front-end > JS Tutorial > jQuery miscellaneous methods

jQuery miscellaneous methods

巴扎黑
Release: 2017-06-26 14:32:14
Original
1140 people have browsed it

Previous words

Miscellaneous methods are actually tool class methods, but because they are not methods defined on the jQuery constructor, they cannot be called tool methods. This article will introduce in detail the miscellaneous methods in jQuery

Data operations

[data()]

This method is used to store any arbitrary Related data or returns the value stored in the data of the given name of the first element in the matched set of elements

data( key, value )
data( obj )
data( key )
data()
Copy after login
$("body").data("foo", 52);
$("body").data("bar", { myType: "test", count: 40 });
$("body").data({ baz: [ 1, 2, 3 ] });

console.log($("body").data("foo"));//52console.log($("body").data());//{foo: 52, bar: Object, baz: Array(3)}
Copy after login

If using native javascript, equivalent to

document.body.foo = 52;
console.log(document.body.foo);//52
Copy after login

【removeData()】

The removeData() method allows the removal of values ​​bound with .data(). When called with the name argument, .removeData() will remove that unique value. When called without any arguments, all values ​​will be removed. jQuery's internal .data() cache does not affect any HTML5 data-attributes in the document. These attributes can be removed using .removeAttr()

When using .removeData("name"), if Without this attribute name in the internal data cache, jQuery will try to find a data-attribute on the element. To avoid repeatedly querying the data- attribute, set the name to either null or undefined (e.g. .data("name", undefined)) instead of using .removeData()

removeData( [name] ) // [name]:String 要移除的存储数据名removeData( [list] ) // [list]:Array,String 一个数组或空间分隔的字符串命名要删除的数据块
Copy after login
$('body').data("test1", "VALUE-1")
         .data("test2", "VALUE-2");
console.log($('body').data());//{test1: "VALUE-1", test2: "VALUE-2"}$('body').removeData("test1");
console.log($('body').data());//{test1: "VALUE-1", test2: "VALUE-2"}
Copy after login

If you use native javascript, it is equivalent to

document.body.foo = 52;
console.log(document.body.foo);//52delete document.body.foo;
console.log(document.body.foo);
Copy after login

Queue operation

【queue()】

Display or operate the function queue that has been executed on the matching element

queue( [queueName ] ) //queueName : String 一个含有队列名的字符串。默认是 fx,标准的动画队列
queue( [queueName ], newQueue ) //newQueue:Array 一个替换当前列队内容的函数数组
queue( [queueName ], callback( next ) )//callback( next ):Function() 将要添加到队列中的新函数。当该函数被调用时,会从弹出队列中的下一个元素
Copy after login
var div = $("div");
div.show("slow");
div.animate({left:'+=200'},2000);var n = div.queue('fx');
console.log(n.length);//2
Copy after login

【clearQueue()】

From the queue Remove all unexecuted items

clearQueue( [queueName ] )
Copy after login

Collection operation

【each()】

Traverse a jQuery object , execute a function for each matching element

each( function(index, function(index, Element)) )
Copy after login
$( "li" ).each(function( index ) {
  console.log( index + ": "" + $(this).text() );
});
Copy after login

【add()】

 add() method adds elements to the matching element gather. The argument to the add() method can accept almost any $(), including a jQuery selector expression, DOM element, or HTML fragment reference

add( selector )
add( elements )
add( html )
add( jQuery object )
add( selector, context )
Copy after login
$('li').add('p')
$('li').add('<p id="new">new paragraph</p>')
Copy after login
<script src="http://cdn.bootcss.com/jquery/1.12.4/jquery.min.js?1.1.11"></script><ul>
  <li>list item 1</li>
  <li>list item 2</li>
  <li>list item 3</li></ul><div>div</div><button id="btn">按钮</button><script>$('#btn').click(function(){
    $('li').add('div').css('background', 'lightgreen');
})</script>
Copy after login


【get()】

Get the corresponding DOM element by retrieving the matching jQuery object

<span style="color: #000000;">get( [index ] ) index:Number 从0开始计数,用来确定获取哪个元素<br></span>
Copy after login
$( "li" ).get( 0 )
Copy after login

【index()】

Search the index value of the given element from the matching elements, counting from 0

index( [selector或element] )
Copy after login

If not If you pass any parameters to the .index() method, the return value is the position of the first element in the jQuery object relative to its sibling elements

If .index() is called on a set of elements, and the parameter is a For DOM elements or jQuery objects, the return value of .index() is the position of the passed in element relative to the original collection.

If the parameter is a selector, the return value of .index() is the position of the original element relative to the element matched by the selector. If no matching element is found, .index() returns -1

$('#bar').index();
listItem.index('li');
$('li').index($('li:gt(0)'));
Copy after login

【toArray()】

Returns a DOM containing all the jQuery objects in the collection Array of elements

toArray() 这个方法不接受任何参数
Copy after login
//[<li id="foo">, <li id="bar">]alert($('li').toArray());
Copy after login

Index filter

The index selector is part of the jQuery filter selector. At the same time, there are also index-related methods with similar functions, including eq(), first(), and last()

【eq()】

The eq() method matches elements Which element of the collection is at the specified index. The eq() method can accept an integer as a parameter, with 0 as the base. If the integer is a negative number, counting starts from the last element in the collection

<script src="http://cdn.bootcss.com/jquery/1.12.4/jquery.min.js?1.1.11"></script><ul><li>list item 1</li><li>list item 2</li><li>list item 3</li><li>list item 4</li><li>list item 5</li></ul><button id="btn1">按钮一</button><button id="btn2">按钮二</button><button id="btn3">按钮三</button><script>$('#btn1').click(function(){
    $('li').eq(0).css('border','1px solid red');    
})
$('#btn2').click(function(){
    $('li').eq(-1).css('border','1px solid blue');    
})
$('#btn3').click(function(){
    $('li').eq(2).css('border','1px solid green');    
})</script>
Copy after login


##【first()】

 first( ) method obtains the first element in the matching element set. This method does not accept parameters.

【last()】

The last() method obtains the last element in the matching element set. This method does not accept parameters. Accepts parameters

<script src="http://cdn.bootcss.com/jquery/1.12.4/jquery.min.js?1.1.11"></script><ul><li>list item 1</li><li>list item 2</li><li>list item 3</li><li>list item 4</li><li>list item 5</li></ul><button id="btn1">按钮一</button><button id="btn2">按钮二</button><script>$('#btn1').click(function(){
    $('li').first().css('border','1px solid red');    
})
$('#btn2').click(function(){
    $('li').last().css('border','1px solid blue');    
})</script>
Copy after login


[end()]

Terminates the latest filtering operation in the current chain and returns the matching element Previous state

end() 这个方法不接受任何参数
Copy after login
The end() method is mainly used in jQuery's chained properties. When not using chaining, we usually just call the previous object on the variable name, so we don't need to manipulate the stack. When using end(), we can call all the required methods at once

$('ul.first').find('.foo').css('background-color', 'red')
  .end().find('.bar').css('background-color', 'green');
Copy after login

  在上面的代码中,首先在链式用法中只在第一个列表中查找样式为 foo 的项目,并将其背景色变成红色。然后 end() 返回调用 find() 之前的状态。因此,第二次 find() 将只会查找

    中的 '.bar',而不是继续在
  • 中进行查找,结果是将匹配到的元素的背景色变成绿色

     

    内容过滤

      jQuery选择器中包括内容过滤选择器,而jQuery中也存在功能类似的内容过滤的方法,包括has()、filter()、is()、not()、map()、slice()

    【has()】

      has()方法用于筛选匹配元素集合中有相匹配的选择器或DOM元素的后代元素的父元素

    <script src="http://cdn.bootcss.com/jquery/1.12.4/jquery.min.js?1.1.11"></script><ul><li>list item 1</li><li>list item 2<ul>  <li>list item 2-a</li>  <li>list item 2-b</li></ul></li><li>list item 3</li></ul><button id="btn">按钮</button><script>$('#btn').click(function(){
        $('li').has('ul').css('border', '1px solid lightblue');
    })</script>
    Copy after login


    【map()】

      map()方法通过一个函数匹配当前集合中的每个元素

      作为参数的函数有两个参数,第一个参照是匹配集合中的元素索引,第二个参数是当前索引的DOM元素对象

    <script src="http://cdn.bootcss.com/jquery/1.12.4/jquery.min.js?1.1.11"></script><input value="text"><input value="text"><input value="text"><button id="btn">按钮</button><script>$('#btn').click(function(){
        $('input').map(function(index,dom){
            dom.value += index;
        });
    })</script>
    Copy after login


    【filter()】

      filter()方法从匹配的元素集合中筛选出指定的元素,参数可以是一个选择器字符串、一个或多个DOM元素、jQuery对象或一个函数  

    <script src="http://cdn.bootcss.com/jquery/1.12.4/jquery.min.js?1.1.11"></script><ul><li>list item 1</li><li>list item 2</li><li>list item 3</li><li>list item 4</li><li>list item 5</li></ul><button id="btn">按钮</button><script>$('#btn').click(function(){
        $('li').filter(':even').css('border','1px solid lightgreen')
    })</script>
    Copy after login


      filter()方法中作为参数的函数有两个参数,第一个参照是匹配集合中的元素索引,第二个参数是当前索引的DOM元素对象。如果函数返回值为true,则该元素保留;否则,该元素在匹配集合中被去除 

    <script src="http://cdn.bootcss.com/jquery/1.12.4/jquery.min.js?1.1.11"></script><ul><li>list item 1</li><li>list item 2</li><li>list item 3</li><li>list item 4</li><li>list item 5</li></ul><button id="btn">按钮</button><script>$('#btn').click(function(){
        $('li').filter(function(index,dom){if(!(index % 3)){
                $(dom).css('border','1px solid lightgreen')return true;
            }
        })
    })</script>
    Copy after login


    【not()】

      not()方法与filter()方法正好相反,它从匹配的元素集合中移除指定的元素,参数可以是一个选择器字符串、一个或多个DOM元素、jQuery对象或一个函数 

    <script src="http://cdn.bootcss.com/jquery/1.12.4/jquery.min.js?1.1.11"></script><ul><li>list item 1</li><li>list item 2</li><li>list item 3</li><li>list item 4</li><li>list item 5</li></ul><button id="btn">按钮</button><script>$('#btn').click(function(){
        $('li').not(':even').css('border','1px solid lightgreen')
    })</script>
    Copy after login


      not()方法中作为参数的函数有两个参数,第一个参照是匹配集合中的元素索引,第二个参数是当前索引的DOM元素对象。如果函数返回值为true,则该元素被去除;否则,该元素在匹配集合中保留

    <script src="http://cdn.bootcss.com/jquery/1.12.4/jquery.min.js?1.1.11"></script><ul><li>list item 1</li><li>list item 2</li><li>list item 3</li><li>list item 4</li><li>list item 5</li></ul><button id="btn">按钮</button><script>$('#btn').click(function(){
        $('li').not(function(index,dom){if(!(index % 3)){
                $(dom).css('border','1px solid lightgreen')return true;
            }
        })
    })</script>
    Copy after login


    【is()】

      is()方法用于判断当前元素是否与参数相匹配,如果匹配,则返回true;否则,返回false。参数可以是一个选择器,DOM元素,jQuery对象或函数

    <script src="http://cdn.bootcss.com/jquery/1.12.4/jquery.min.js?1.1.11"></script><ul><li>list item 1</li><li>list item 2</li><li>list item 3</li><li>list item 4</li><li>list item 5</li></ul><script>$('li').click(function(){if($(this).is(':contains("2")')){
            $(this).css('border','1px solid black')
        }
    })</script>
    Copy after login


      is()方法中作为参数的函数有两个参数,第一个参照是匹配集合中的元素索引,第二个参数是当前索引的DOM元素对象。如果函数返回true,is()方法也返回true,如果函数返回false,is()方法也返回false

    <script src="http://cdn.bootcss.com/jquery/1.12.4/jquery.min.js?1.1.11"></script><ul><li>list item 1</li><li>list item 2</li><li>list item 3</li><li>list item 4</li><li>list item 5</li></ul><div id="result"></div><script>var i = 0;
    $('li').click(function(){++i;if($(this).is(function(index,dom){
            $('#result').html(dom.innerHTML);if(i%2){return true;    
            }
        })){
             $(this).css('border','1px solid black')
        }
    })</script>
    Copy after login


    【slice()】

      slice()方法根据指定的下标范围,过滤匹配的元素集合,并生成一个新的jQuery对象 

      slice(start[,end])方法接受两个参数:start和end

      start是一个整数,从0开始计数的下标。代表将要被选择的元素的起始下标。如果指定的下标是一个负数,那么代表从末尾开始计数

      end是一个整数,从0开始计数的下标。代表将要被选择的元素的结束下标。如果指定的下标是一个负数,那么代表从末尾开始计数。如果忽略此参数,则选择的范围是从start开始,一直到最后

    <script src="http://cdn.bootcss.com/jquery/1.12.4/jquery.min.js?1.1.11"></script><ul>
      <li>list item 1</li>
      <li>list item 2</li>
      <li>list item 3</li>
      <li>list item 4</li>
      <li>list item 5</li></ul><button id="btn">按钮</button><script>$('#btn').click(function(){
        $('li').slice(2,4).css('background', 'red');
    })</script>
    Copy after login


     

The above is the detailed content of jQuery miscellaneous methods. 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