Home  >  Article  >  Web Front-end  >  jquery some code collection

jquery some code collection

炎欲天舞
炎欲天舞Original
2017-08-04 14:01:421129browse

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");


//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>

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");

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;);

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>

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;);

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

    a.toggleClass(&#39;blueButton&#39;);

7. How to set up IE-specific functions

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

8. How to use jQuery to replace an element

    $(&#39;#thatp&#39;).replaceWith(&#39;fnuh&#39;);

9. How to verify whether an element is empty

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

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;
    });

11. How to bind a function to an event

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

12. How to append or add html to an element

    $(&#39;#lal&#39;).append(&#39;sometext&#39;);

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

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

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();

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;);

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");
    });

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

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

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

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

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();

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及之后版本

21. How Replace words in a string

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

22. How to disable the right-click context menu

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

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();

24. How to check for a Whether the element exists

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

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");
        }
    });

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]);
            }
        });
    });

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);

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

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

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);

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

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

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

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

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

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

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();

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

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

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();

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

    $(&#39;#searchBox&#39;).closest(&#39;p&#39;);

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;
    };

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;
    });

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

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

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;);
    });

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

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

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

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

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

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

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>

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

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

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

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

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

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

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     }

49. 如何让cookie过期

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

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();

 

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:
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