Home Web Front-end JS Tutorial jquery some code collection

jquery some code collection

Aug 04, 2017 pm 02:01 PM
jquery collect

1. How to create nested filters

// Filters that allow you to reduce the matching elements in a collection,

// Only those that match the given selector Matching parts. In this case,

//The query deletes any child nodes that do not (:not) have (:has)

//Contains the child node with class "selected" (.selected).

.filter(":not(:has(.selected))")

2. How to reuse element search

    var allItems = $("p.item");
    var keepList = $("p#container1 p.item");
Copy after login


//Now you can continue working with these jQuery objects. For example,

// Cut the "Keep list" based on the check box, the name of the check box

// conform to

   <p>class names:
    $(formToLookAt + " input:checked").each(function () {
        keepList = keepList.filter("." + $(this).attr("name"));
    });
   </p>
Copy after login

3. Any use of has () to check Whether an element contains a certain class or element

//jQuery 1.4.* includes support for this has method. This method finds out

//Whether an element contains another element class or anything else

//What you are looking for and want to operate on .

      $("input").has(".email").addClass("email_icon");
Copy after login

4. How to use jQuery to switch style sheets

//Find out the media type (media-type) you want to switch, and then set the href to the new style sheet.

    $(&#39;link[media="screen"]&#39;).attr(&#39;href&#39;, &#39;Alternative.css&#39;);
Copy after login

5. How to limit the selection range (based on optimization purposes)

//Use the tag name as the prefix of the class name as much as possible,

//This way jQuery will not It takes more time to search for the element you want. One more thing to remember is that the more specific the operation of the elements on your page, the more specific the operation of the elements on your page, the more you can reduce the time of execution and search.

    var in_stock = $(&#39;#shopping_cart_items input.is_in_stock&#39;);
    <ul id="shopping_cart_items">
        <li><input type="radio" value="Item-X" name="item" class="is_in_stock" />Item X</li>
        <li><input type="radio" value="Item-Y" name="item" class="3-5_days" />Item Y</li>
        <li><input type="radio" value="Item-Z" name="item" class="unknown" />Item Z</li>
    </ul>
Copy after login

6. How to use ToggleClass correctly

                                                                                                                                                                                              The toggle class allows you to add or delete a certain class based on whether it exists. kind.

//In this case some developers use:

        a.hasClass(&#39;blueButton&#39;) ? a.removeClass(&#39;blueButton&#39;) : a.addClass(&#39;blueButton&#39;);
Copy after login

//toggleClass allows you to do this easily using the following statement

    a.toggleClass(&#39;blueButton&#39;);
Copy after login

7. How to set up IE-specific functions

    if ($.browser.msie) {       // Internet Explorer其实不那么好用 
    }
Copy after login

8. How to use jQuery to replace an element

    $(&#39;#thatp&#39;).replaceWith(&#39;fnuh&#39;);
Copy after login

9. How to verify whether an element is empty

    if ($(&#39;#keks&#39;).html().trim()) {       //什么都没有找到; 
    }
Copy after login

10. How to start from Find the index number of an element in an unsorted collection

    $("ul > li").click(function () {
        var index = $(this).prevAll().length;
    });
Copy after login

11. How to bind a function to an event

    $(&#39;#foo&#39;).bind(&#39;click&#39;, function () {
        alert(&#39;User clicked on "foo."&#39;);
    });
Copy after login

12. How to append or add html to an element

    $(&#39;#lal&#39;).append(&#39;sometext&#39;);
Copy after login

13. How to use object literals to define attributes when creating elements

    var e = $("", { href: "#", class: "a-class another-class", title: "..." });
Copy after login

14. How to use multiple attributes for filtering

                                                

//This accuracy-based approach is useful when using many similar input elements of different types

      var elements = $(&#39;#someid input[type=sometype][value=somevalue]&#39;).get();
Copy after login

15. How to preload images using jQuery

    jQuery.preloadImages = function () {
        for (var i = 0; i < arguments.length; i++) {
            $("<img />").attr(&#39;src&#39;, arguments[i]);
        }
    };
        //用法 $.preloadImages(&#39;image1.gif&#39;, &#39;/path/to/image2.png&#39;, &#39;some/image3.jpg&#39;);
Copy after login

16. How to set event handlers for any element that matches a selector

    $(&#39;button.someClass&#39;).live(&#39;click&#39;, someFunction);        //注意,在jQuery 1.4.2中,delegate和undelegate选项
        //被引入代替live,因为它们提供了更好的上下文支持
        //例如,就table来说,以前你会用 
     //.live()  
    $("table").each(function () {
        $("td", this).live("hover", function () {
            $(this).toggleClass("hover");
        });
    });       //现在用 
    $("table").delegate("td", "hover", function () {
        $(this).toggleClass("hover");
    });
Copy after login

17. How to find an option element that has been selected

    $(&#39;#someElement&#39;).find(&#39;option:selected&#39;);
Copy after login

18. How to hide an option element that contains Elements with a certain value text

    $("p.value:contains(&#39;thetextvalue&#39;)").hide();
Copy after login

19. If you automatically scroll to a certain area on the page

    jQuery.fn.autoscroll = function (selector) { 
        $(&#39;html,body&#39;).animate( { scrollTop: $(this ).offset().top },        500        );    }
 
       //然后像这样来滚动到你希望去到的class/area上。 
   $(&#39;.area_name&#39;).autoscroll();
Copy after login

20. How to detect various browsers

    if( $.browser.safari) //检测Safari 
    if ($.browser.msie && $.browser.version > 6 ) //检测IE6及之后版本 
    if ($.browser.msie && $.browser.version <= 6 ) //检测IE6及之前版本 
    if($.browser.mozilla && $.browser.version >= &#39;1.8&#39; ) //检测FireFox 2及之后版本
Copy after login

21. How Replace words in a string

    var el = $(&#39;#id&#39;); el.html(el.html().replace(/word/ig, &#39;&#39;));
Copy after login

22. How to disable the right-click context menu

    $(document).bind(&#39;contextmenu&#39;, function (e) { 
         return false ;    
     });
Copy after login

23. How to define a custom selector

   $.expr[&#39;:&#39;].mycustomselector = function(element, index, meta, stack){  
    // element- 一个DOM元素
        // index – 栈中的当前循环索引
        // meta – 有关选择器的元数据
        // stack – 要循环的所有元素的栈
        // 如果包含了当前元素就返回true  
        // 如果不包含当前元素就返回false };  
        // 定制选择器的用法: 
     $(&#39;.someClasses:test&#39;).doSomething();
Copy after login

24. How to check for a Whether the element exists

    if ($(&#39;#somep&#39; ).length) {      //你妹,终于找到了 
    }
Copy after login

25. How to use jQuery to detect right and left mouse clicks

    $("#someelement").live(&#39;click&#39;, function (e) {
        if ((!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1)) {
            alert("Left Mouse Button Clicked");
        } else if (e.button == 2) {
            alert("Right Mouse Button Clicked");
        }
    });
Copy after login

26. How to display or delete the default value in the input field

           //This code shows how to retain a default value in a text type input field when the user does not enter a value

                               

    $(".swap").each(function (i) {
        wap_val[i] = $(this).val();
        $(this).focusin(function () {
            if ($(this).val() == swap_val[i]) {
                $(this).val("");
            }
        }).focusout(function () {
            if ($.trim($(this).val()) == "") {
                $(this).val(swap_val[i]);
            }
        });
    });
Copy after login

27. 如何在一段时间之后自动隐藏或关闭元素(支持1.4版本)

       //这是1.3.2中我们使用setTimeout来实现的方式
    setTimeout(function () {
        $(&#39;.myp&#39;).hide(&#39;blind&#39;, {}, 500)
    }, 5000);
    //而这是在1.4中可以使用delay()这一功能来实现的方式(这很像是休眠) 
    $(".myp").delay(5000).hide(&#39;blind&#39;, {}, 500);
Copy after login

28. 如何把已创建的元素动态地添加到DOM中

   var newp = $(&#39;&#39;); 
       newp.attr(&#39;id&#39;, &#39;myNewp&#39;).appendTo(&#39;body&#39;);
Copy after login

29. 如何限制“Text-Area”域中的字符的个数

    jQuery.fn.maxLength = function (max) {
        this.each(function () {
            var type = this.tagName.toLowerCase();
            var inputType = this.type ? this.type.toLowerCase() : null;
            if (type == "input" && inputType == "text" || inputType == "password") {                this.maxLength = max;
            }
            else if (type == "textarea") {
                this.onkeypress = function (e) {
                    var ob = e || event;
                    var keyCode = ob.keyCode;
                    var hasSelection = document.selection
                        ? document.selection.createRange().text.length > 0
                        : this.selectionStart != this.selectionEnd;
                    return !(this.value.length >= max
                        && (keyCode > 50 || keyCode == 32 || keyCode == 0 || keyCode == 13)
                        && !ob.ctrlKey && !ob.altKey && !hasSelection);
                };
                this.onkeyup = function () {
                    if (this.value.length > max) {
                        this.value = this.value.substring(0, max);
                    }
                };
            }
        });
    };
        //用法 $(&#39;#mytextarea&#39;).maxLength(500);
Copy after login

30. 如何为函数创建一个基本的测试

    //把测试单独放在模块中 
    module("Module B");
    test("some other test", function () {
        //指明测试内部预期有多少要运行的断言         expect(2);
        //一个比较断言,相当于JUnit的assertEquals  
        equals(true, false, "failing test");
        equals(true, true, "passing test");
    });
Copy after login

31. 如何在jQuery中克隆一个元素

    var cloned = $(&#39;#somep&#39;).clone();
Copy after login

32. 在jQuery中如何测试某个元素是否可见

    if ($(element).is(&#39;:visible&#39;) ) {        //该元素是可见的 
    }
Copy after login

33. 如何把一个元素放在屏幕的中心位置

    jQuery.fn.center = function () {
        this.css(&#39;position&#39;, &#39;absolute&#39;);
        this.css(&#39;top&#39;, ($(window).height() - this.height())                         
                       / +$(window).scrollTop() + &#39;px&#39;);
        this.css(&#39;left&#39;, ($(window).width() - this.width())                          
                       / 2 + $(window).scrollLeft() + &#39;px&#39;);
        return this;
    }
       //这样来使用上面的函数: $(element).center();
Copy after login

34. 如何把有着某个特定名称的所有元素的值都放到一个数组中

    var arrInputValues = new Array(); 
    $("input[name=&#39;table[]&#39;]").each(function () {
       arrInputValues.push($(this ).val());    });
Copy after login

35. 如何从元素中除去HTML

    (function ($) {
        $.fn.stripHtml = function () {
            var regexp = /<("[^"]*"|&#39;[^&#39;]*&#39;|[^&#39;">])*>/gi;
            this.each(function () {
                $(this).html($(this).html().replace(regexp, ""));
            });
            return $(this);
        }
    })(jQuery);
        //用法: $(&#39;p&#39;).stripHtml();
Copy after login

36. 如何使用closest来取得父元素

    $(&#39;#searchBox&#39;).closest(&#39;p&#39;);
Copy after login

37. 如何使用Firebug和Firefox来记录jQuery事件日志

       // 允许链式日志记录
       // 用法: 
    $(&#39;#somep&#39;).hide().log(&#39;p hidden&#39;).addClass(&#39;someClass&#39;);
    jQuery.log = jQuery.fn.log = function (msg) {
        if (console) {
            console.log("%s: %o", msg, this);
        }
        return this;
    };
Copy after login

38. 如何强制在弹出窗口中打开链接

    jQuery(&#39;a.popup&#39;).live(&#39;click&#39;, function () {
        newwindow = window.open($(this).attr(&#39;href&#39;), &#39;&#39;, &#39;height=200,width=150&#39;);
        if (window.focus) {
            newwindow.focus();
        } return false;
    });
Copy after login

39. 如何强制在新的选项卡中打开链接

    jQuery(&#39;a.newTab&#39;).live(&#39;click&#39;, function () {
        newwindow = window.open($(this).href);
        jQuery(this).target = "_blank";
        return false;
    });
Copy after login

40. 在jQuery中如何使用.siblings()来选择同辈元素

        // 不这样做 
    $(&#39;#nav li&#39;).click(function () {
        $(&#39;#nav li&#39;).removeClass(&#39;active&#39;);
        $(this).addClass(&#39;active&#39;);
    });
        //替代做法是
    $(&#39;#nav li&#39;).click(function () {
        $(this).addClass(&#39;active&#39;).siblings().removeClass(&#39;active&#39;);
    });
Copy after login

41. 如何切换页面上的所有复选框

    var tog = false ;    // 或者为true,如果它们在加载时为被选中状态的话
    $(&#39;a&#39;).click(function () {
        $("input[type=checkbox]").attr("checked", !tog);
        tog = !tog;
    });
Copy after login

42. 如何基于一些输入文本来过滤一个元素列表

       //如果元素的值和输入的文本相匹配的话  
       //该元素将被返回
    $(&#39;.someClass&#39;).filter(function () {
        return $(this).attr(&#39;value&#39;) == $(&#39;input#someId&#39;).val();
    })
Copy after login

43. 如何获得鼠标垫光标位置x和y

    $(document).ready(function () {
        $(document).mousemove(function (e) {
            $(&#39;#XY&#39;).html("X Axis : " + e.pageX + " | Y Axis " + e.pageY);
        });
    });
Copy after login

44. 如何把整个的列表元素(List Element,LI)变成可点击的

    $("ul li").click(function () {
        window.location = $(this).find("a").attr("href");
        return false;
    });
    <ul>
        <li><a href="#">Link 1</a></li>
        <li><a href="#">Link 2</a></li>
        <li><a href="#">Link 3</a></li>
        <li><a href="#">Link 4</a></li>
    </ul>
Copy after login

45. 如何使用jQuery来解析XML(基本的例子)

    function parseXml(xml) {
        //找到每个Tutorial并打印出author  
        $(xml).find("Tutorial").each(function () {
            $("#output").append($(this).attr("author") + "");
        });
    }
Copy after login

46. 如何检查图像是否已经被完全加载进来

    $(&#39;#theImage&#39;).attr(&#39;src&#39;, &#39;image.jpg&#39;).load(function () {
        alert(&#39;This Image Has Been Loaded&#39;);
      });
Copy after login

47. 如何使用jQuery来为事件指定命名空间

    //事件可以这样绑定命名空间
    $(&#39;input&#39;).bind(&#39;blur.validation&#39;, function (e) {
        // ...  
    });
 
    //data方法也接受命名空间 
    $(&#39;input&#39;).data(&#39;validation.isValid&#39;, true);
Copy after login

48. 如何检查cookie是否启用

     var dt = new Date();
     dt.setSeconds(dt.getSeconds() + 60);
     document.cookie = "cookietest=1; expires=" + dt.toGMTString();
     var cookiesEnabled = document.cookie.indexOf("cookietest=") != -1;
     if (!cookiesEnabled) {
        //没有启用cookie     }
Copy after login

49. 如何让cookie过期

    var date = new Date();
    date.setTime(date.getTime() + (x * 60 * 1000));
    $.cookie(&#39;example&#39;, &#39;foo&#39;, { expires: date });
Copy after login

50. 如何使用一个可点击的链接来替换页面中任何的URL

    $.fn.replaceUrl = function () {
        var regexp =
            /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi;
        this.each(function () {
            $(this).html(
               $(this).html().replace(regexp, &#39;<a href="$1">$1</a>&#39;)
            );
        });
        return $(this);
    }
       //用法  $(&#39;p&#39;).replaceUrl();
Copy after login

 

The above is the detailed content of jquery some code collection. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of jQuery reference methods: Quick start guide Detailed explanation of jQuery reference methods: Quick start guide Feb 27, 2024 pm 06:45 PM

Detailed explanation of jQuery reference method: Quick start guide jQuery is a popular JavaScript library that is widely used in website development. It simplifies JavaScript programming and provides developers with rich functions and features. This article will introduce jQuery's reference method in detail and provide specific code examples to help readers get started quickly. Introducing jQuery First, we need to introduce the jQuery library into the HTML file. It can be introduced through a CDN link or downloaded

How to quickly collect hardwood in Stardew Valley How to quickly collect hardwood in Stardew Valley Mar 26, 2024 am 11:21 AM

Hardwood is an important synthetic material in Stardew Valley. We can have many uses in the game, so we can stock it up in our daily life. What are the specific ways to obtain hardwood? Below we will bring you Stardew Valley. You can refer to the way to obtain hardwood in Monogatari if necessary. Ways to obtain hardwood in Stardew Valley 1. Go to the secret forest every day to dig tree stumps to quickly obtain hardwood. 2. There is a chance to obtain mahogany seeds by mining tree stumps and fighting monsters in the secret forest. 3. Planting seeds in the yard will produce mahogany trees. 4. Finally, after mining mahogany, you can quickly obtain a large amount of hardwood.

How to use PUT request method in jQuery? How to use PUT request method in jQuery? Feb 28, 2024 pm 03:12 PM

How to use PUT request method in jQuery? In jQuery, the method of sending a PUT request is similar to sending other types of requests, but you need to pay attention to some details and parameter settings. PUT requests are typically used to update resources, such as updating data in a database or updating files on the server. The following is a specific code example using the PUT request method in jQuery. First, make sure you include the jQuery library file, then you can send a PUT request via: $.ajax({u

Install CentOS on mobile phones and install CentOS 7 on mobile phones Install CentOS on mobile phones and install CentOS 7 on mobile phones Feb 29, 2024 pm 02:43 PM

Preface As keen Linux users, we often encounter the need to install CentOS or CentOS7 on mobile phones. Although mobile phones are not the best Linux running platform, sometimes we need to perform some Linux-related operations or development work on mobile phones. In this article, we will discuss in detail how to install CentOS or CentOS7 on your phone. Installing CentOS on a mobile phone To install CentOS on a mobile phone, we first need a mobile phone that supports virtualization technology, such as a mobile phone that supports Android system. Then we can use a terminal emulator application such as Termux to simulate the Linux environment. In Termux, we can Use a package manager to install CentOS

How to remove the height attribute of an element with jQuery? How to remove the height attribute of an element with jQuery? Feb 28, 2024 am 08:39 AM

How to remove the height attribute of an element with jQuery? In front-end development, we often encounter the need to manipulate the height attributes of elements. Sometimes, we may need to dynamically change the height of an element, and sometimes we need to remove the height attribute of an element. This article will introduce how to use jQuery to remove the height attribute of an element and provide specific code examples. Before using jQuery to operate the height attribute, we first need to understand the height attribute in CSS. The height attribute is used to set the height of an element

jQuery Tips: Quickly modify the text of all a tags on the page jQuery Tips: Quickly modify the text of all a tags on the page Feb 28, 2024 pm 09:06 PM

Title: jQuery Tips: Quickly modify the text of all a tags on the page In web development, we often need to modify and operate elements on the page. When using jQuery, sometimes you need to modify the text content of all a tags in the page at once, which can save time and energy. The following will introduce how to use jQuery to quickly modify the text of all a tags on the page, and give specific code examples. First, we need to introduce the jQuery library file and ensure that the following code is introduced into the page: &lt

Use jQuery to modify the text content of all a tags Use jQuery to modify the text content of all a tags Feb 28, 2024 pm 05:42 PM

Title: Use jQuery to modify the text content of all a tags. jQuery is a popular JavaScript library that is widely used to handle DOM operations. In web development, we often encounter the need to modify the text content of the link tag (a tag) on ​​the page. This article will explain how to use jQuery to achieve this goal, and provide specific code examples. First, we need to introduce the jQuery library into the page. Add the following code in the HTML file:

Understand the role and application scenarios of eq in jQuery Understand the role and application scenarios of eq in jQuery Feb 28, 2024 pm 01:15 PM

jQuery is a popular JavaScript library that is widely used to handle DOM manipulation and event handling in web pages. In jQuery, the eq() method is used to select elements at a specified index position. The specific usage and application scenarios are as follows. In jQuery, the eq() method selects the element at a specified index position. Index positions start counting from 0, i.e. the index of the first element is 0, the index of the second element is 1, and so on. The syntax of the eq() method is as follows: $("s

See all articles