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

Absolute introduction to jQuery

PHP中文网
Release: 2016-05-16 18:54:17
Original
856 people have browsed it

For those who want to learn jquery, you can read this entry-level article.

1. jQuery GO
jQuery provides a powerful way to read and process document DOM, providing convenience for dynamically operating document DOM.

$(document).ready(function() { 
$("a").click(function() { 
alert("Hello world!"); 
}); 
});
Copy after login

Clicking any link in the document will trigger the alert() event
$ is an alias for the jQuery class, so $() constructs a new jQuery object. The function click() is a method of this jQuery object. It binds a click event to all selected tags (here are all a tags), and executes the alert method it provides when the event is triggered. Like this Using coding gives a better sense of separation of structure and behavior.
2. Selectors and events
jQuery provides two ways to select HTML elements. The first is to use CSS and Xpath selectors to combine to form a string and send it to jQuery's constructor (such as: $(" p > ul a")); the second is to use several methods of jQuery objects. These two methods can also be combined and mixed.

<ul id=”orderedlist”> 
<li>食品</li> 
<li>服装</li> 
<li>电子</li> 
</ul>
Copy after login

Use jQuery to find ul in the document as follows: replace js document.getElementById('orderlist');

$(document).ready(function() { 
$("#orderedlist").addClass("red"); 
});
Copy after login

$( "#..") method can find the element with the specified ID.
Add a style to its child nodes, as follows:

$(document).ready(function() { 
$("#orderedlist > li").addClass("blue"); 
});
Copy after login

The style switches when the mouse moves to or away from the

  • item, as follows:

    $(document).ready(function() { 
    $("#orderedlist li:last").hover(function() { 
    $(this).addClass("green"); 
    }, function() { 
    $(this).removeClass("green"); 
    }); 
    });
    Copy after login
    <🎜 The difference between >$(#orderedlist li) and $("#orderedlist > li") is that the former is all matching child elements under the parent element, and the latter is only the matching elements among its child elements.

    $(document).ready(function() { 
    $("#orderedlist").find("li").each(function(i) { 
    $(this).html( $(this).html() + " BAM! " + i ); 
    }); 
    });
    Copy after login
    find() allows you to perform a conditional search within the selected element, so $("#orderedlist).find("li") is just like $("#orderedlist li"). The each() method iterates over all li and can do more processing on this basis. Most methods, such as addClass(), can use their own each(). In this example, html(). Used to get the html text of each li, append some text, and set it as the html text of the li

    An operation to reset the form after submitting in ajax mode, as follows:

    $(document).ready(function() { 
    // use this to reset a single form 
    $("#reset").click(function() { 
    $("#form")[0].reset(); 
    }); 
    });
    Copy after login
    Of course You can reset a form

    $(document).ready(function() { 
    // use this to reset several forms at once 
    $("#reset").click(function() { 
    $("form").each(function() { 
    this.reset(); 
    }); 
    }); 
    });
    Copy after login
    Filter selector

    Another problem you may have to face is that you don’t want certain elements to be selected. jQuery provides filter() and not(. ) method to solve this problem. filter() uses a filter expression to reduce the selected items that do not match the filter expression, and not() is used to cancel all selected items that match the filter expression. Consider an unordered list, and you want to Select all li elements that do not have a ul child element.

    $(document).ready(function() { 
    $("li").not("[ul]").css("border", "1px solid black"); 
    });
    Copy after login
    The [expression] syntax in the above code comes from XPath and can be used as a filter on child elements and attributes. , for example, you may want to select all links with the name attribute:

    $(document).ready(function() { 
    $("a[name]").background("#eee"); //原文为“$("a[@name]").background("#eee");”在jQuery1.2及以上版本中,@符号应该去除 
    });
    Copy after login
    A more common situation is to select links by name. You may need to select a link with a unique href attribute, which varies depending on the situation. The understanding of href under different browsers may be inconsistent, so we use partial matching ("*=") [includes] instead of full matching ("="):

    $(document).ready(function() { 
    $("a[href*=/content/gallery]").click(function() { 
    // do something with all links that point somewhere to /content/gallery 
    }); 
    });
    Copy after login
    Until now , selectors are used to select child elements or filter elements. Another situation is to select the previous or next element, such as a FAQ page, the answer will be hidden first, and when the question is clicked, the answer will be displayed, jQuery code As follows:

    $(document).ready(function() { 
    $(&#39;#faq&#39;).find(&#39;dd&#39;).hide().end().find(&#39;dt&#39;).click(function() { 
    var answer = $(this).next(); 
    if (answer.is(&#39;:visible&#39;)) { 
    answer.slideUp(); 
    } else { 
    answer.slideDown(); 
    } 
    }); 
    });
    Copy after login
    Here we use some chain expressions to reduce the amount of code, and it looks more intuitive and easier to understand. Like '#faq' is only selected once, using the end() method. The first find() method will end (undone), so we can continue find('dt') later without writing $('#faq').find('dt') again.

    In the click event, we use $(this).next() to find a dd element immediately below dt, which allows us to quickly select the answer below the clicked question
    slideUp(speed ,[callback]) speed slow normal fast or numerical value, the callback function
    dynamically hides all matching elements by changing the height (decreasing upward), optionally triggering a callback function after the hiding is completed.
    This animation effect only adjusts the height of the element and can make the matching element hidden in a "sliding" manner.
    slideDown(speed,[callback])
    Dynamically display all matching elements through height changes (increasing downward), optionally triggering a callback function after the display is completed.
    This animation effect only adjusts the height of the element, allowing matching elements to be displayed in a "sliding" manner.
    In addition to selecting elements at the same level, you can also select elements at the parent level. Maybe you want to highlight the parent element when the user moves the mouse over a link in a certain paragraph of the article. Try this:

    Apply to our In the Hello world example, it can be like this:
    $(document).ready(function() { 
    $("a").hover(function() { 
    $(this).parents("p").addClass("highlight"); 
    }, function() { 
    $(this).parents("p").removeClass("highlight"); 
    }); 
    }); 
    $(document).ready(callback)的缩写法:$(function) 
    $(function() { 
    // code to execute when the DOM is ready 
    });
    Copy after login

    Although these examples can also be implemented without using AJAX, it shows that we will not do that. We use jQuery to generate a p container with the ID "rating".
    $(function() { 
    $("a").click(function() { 
    alert("Hello world!"); 
    }); 
    });
    Copy after login

    $(document).ready(function() { 
    // generate markup 
    var ratingMarkup = ["Please rate: "]; 
    for(var i=1; i <= 5; i++) { 
    ratingMarkup[ratingMarkup.length] = "<a href=&#39;#&#39;>" + i + "</a> "; 
    } 
    // add markup to container and applier click handlers to anchors 
    $("#rating").append( ratingMarkup.join(&#39;&#39;) ).find("a").click(function(e) { 
    e.preventDefault(); 
    // send requests 
    $.post("rate.php", {rating: $(this).html()}, function(xml) { 
    // format result 
    var result = [ 
    "Thanks for rating, current average: ", 
    $("average", xml).text(), 
    ", number of votes: ", 
    $("count", xml).text() 
    ]; 
    // output result 
    $("#rating").html(result.join(&#39;&#39;)); 
    } ); 
    }); 
    });
    Copy after login

    这段代码生成了5个链接,并将它们追加到id为"rating"容器中,当其中一个链接被点击时,该链接标明的分数就会以rating参数形式发送到rate.php,然后,结果将以XML形式会从服务器端传回来,添加到容器中,替代这些链接。
    一个在使用AJAX载入内容时经常发生的问题是:当载入一个事件句柄到一个HTML文档时,还需要在载入内容上应用这些事件,你不得不在内容加载完成后应用这些事件句柄,为了防止代码重复执行,你可能用到如下一个function:

    // lets use the shortcut 
    $(function() { 
    var addClickHandlers = function() { 
    $("a.clickMeToLoadContent").click(function() { 
    $("#target").load(this.href, addClickHandlers); 
    }); 
    }; 
    addClickHandlers(); 
    });
    Copy after login

    现在,addClickHandlers只在DOM载入完成后执行一次,这是在用户每次点击具有clickMeToLoadContent 这个样式的链接并且内容加载完成后.
    请注意addClickHandlers函数是作为一个局部变量定义的,而不是全局变量(如:function addClickHandlers() {...}),这样做是为了防止与其他的全局变量或者函数相冲突.
    另一个常见的问题是关于回调(callback)的参数。你可以通过一个额外的参数指定回调的方法,简单的办法是将这个回调方法包含在一个其它的function中:

    // get some data 
    var foobar = ...; 
    // specify handler, it needs data as a paramter 
    var handler = function(data) { 
    ... 
    }; 
    // add click handler and pass foobar! 
    $(&#39;a&#39;).click( function(event) { handler(foobar); } ); 
    // if you need the context of the original handler, use apply: 
    $(&#39;a&#39;).click( function(event) { handler.apply(this, [foobar]); } );
    Copy after login

    Animate me(让我生动起来):使用FX
    一些动态的效果可以使用 show() 和 hide()来表现:

    $(document).ready(function() { 
    $("a").toggle(function() { 
    $(".stuff").hide(&#39;slow&#39;); 
    }, function() { 
    $(".stuff").show(&#39;fast&#39;); 
    }); 
    });
    Copy after login

    你可以与 animate()联合起来创建一些效果,如一个带渐显的滑动效果:

    $(document).ready(function() { 
    $("a").toggle(function() { 
    $(".stuff").animate({ 
    height: &#39;hide&#39;, 
    opacity: &#39;hide&#39; 
    }, &#39;slow&#39;); 
    }, function() { 
    $(".stuff").animate({ 
    height: &#39;show&#39;, 
    opacity: &#39;show&#39; 
    }, &#39;slow&#39;); 
    }); 
    }); 
    toggle(fn,fn)
    Copy after login

    每次点击后依次调用函数。
    如果点击了一个匹配的元素,则触发指定的第一个函数,当再次点击同一元素时,则触发指定的第二个函数,如果有更多函数,则再次触发,直到最后一个。随后的每次点击都重复对这几个函数的轮番调用。
    可以使用unbind("click")来删除。
    animate(params,options)
    用于创建自定义动画的函数。
    这个函数的关键在于指定动画形式及结果样式属性对象。这个对象中每个属性都表示一个可以变化的样式属性(如“height”、“top”或“opacity”)。
    注意:所有指定的属性必须用骆驼形式,比如用marginLeft代替margin-left.
    而每个属性的值表示这个样式属性到多少时动画结束。如果是一个数值,样式属性就会从当前的值渐变到指定的值。如果使用的是“hide”、“show”或“toggle”这样的字符串值,则会为该属性调用默认的动画形式。

    $("#go1").click(function(){ 
    $("#block1").animate( { width: "90%"}, { queue: false, duration: 5000 } ) 
    .animate( { fontSize: &#39;10em&#39; } , 1000 ) 
    .animate( { borderWidth: 5 }, 1000); 
    }); 
    $("#go2").click(function(){ 
    $("#block2").animate( { width: "90%"}, 1000 ) 
    .animate( { fontSize: &#39;10em&#39; } , 1000 ) 
    .animate( { borderWidth: 5 }, 1000); 
    });
    Copy after login

    使用tablesorter插件(表格排序)
    这个表格排序插件能让我们在客户端按某一列进行排序,引入jQuery和这个插件的js文件,然后告诉插件你想要哪个表格拥有排序功能。
    要测试这个例子,先在starterkit.html中加上像下面这一行的代码:

    <script src="lib/jquery.tablesorter.js" type="text/javascript"></script>
    Copy after login

    然后可以这样调用不着:

    $(document).ready(function() { 
    $("#large").tableSorter(); 
    });
    Copy after login

    现在点击表格的第一行head区域,你可以看到排序的效果,再次点击会按倒过来的顺序进行排列。
    这个表格还可以加一些突出显示的效果,我们可以做这样一个隔行背景色(斑马线)效果:

    $(document).ready(function() { 
    $("#large").tableSorter({ 
    stripingRowClass: [&#39;odd&#39;,&#39;even&#39;], // Class names for striping supplyed as a array. 
    stripRowsOnStartUp: true // Strip rows on tableSorter init. 
    }); 
    });
    Copy after login

    制作自己的插件
    写一个自己的jQuery插件是非常容易的,如果你按照下面的原则来做,可以让其他人也容易地结合使用你的插件.
    1. 为你的插件取一个名字,在这个例子里面我们叫它"foobar".
    2. 创建一个像这样的文件:jquery.[yourpluginname].js,比如我们创建一个jquery.foobar.js
    3. 创建一个或更多的插件方法,使用继承jQuery对象的方式,如:
    4. jQuery.fn.foobar = function() {
    5. // do something
    6. }
    7. 可选的:创建一个用于帮助说明的函数,如:
    8. jQuery.fooBar = {
    9. height: 5,
    10. calculateBar = function() { ... },
    11. checkDependencies = function() { ... }
    12. }
    你现在可以在你的插件中使用这些帮助函数了:
    jQuery.fn.foobar = function() {
    // do something
    jQuery.foobar.checkDependencies(value);
    // do something else
    };
    jQuery.fn.extend(object)
    扩展 jQuery 元素集来提供新的方法(通常用来制作插件)。
    jQuery.fn.extend({
    check: function() {
    return this.each(function() { this.checked = true; });
    },
    uncheck: function() {
    return this.each(function() { this.checked = false; });
    }
    });
    结果:
    $("input[type=checkbox]").check();
    $("input[type=radio]").uncheck();
    13. 可选的l:创建一个默认的初始参数配置,这些配置也可以由用户自行设定,如:
    14. jQuery.fn.foobar = function(options) {
    15. var settings = {
    16. value: 5,
    17. name: "pete",
    18. bar: 655
    19. };
    20. if(options) {
    21. jQuery.extend(settings, options);
    22. }
    23. }
    jQuery.extend(target,obj1,[objN])
    用一个或多个其他对象来扩展一个对象,返回被扩展的对象。
    用于简化继承。

    var settings = { validate: false, limit: 5, name: "foo" }; 
    var options = { validate: true, name: "bar" }; 
    jQuery.extend(settings, options);
    Copy after login

    结果:

    settings == { validate: true, limit: 5, name: "bar" }
    Copy after login

    现在可以无需做任何配置地使用插件了,默认的参数在此时生效:

    $("...").foobar();
    Copy after login

    或者加入这些参数定义:

    $("...").foobar({ 
    value: 123, 
    bar: 9 
    });
    Copy after login

    如果你release你的插件, 你还应该提供一些例子和文档,大部分的插件都具备这些良好的参考文档.
    现在你应该有了写一个插件的基础,让我们试着用这些知识写一个自己的插件.
    很多人试着控制所有的radio或者checkbox是否被选中,比如:

    $("input[type=&#39;checkbox&#39;]").each(function() { 
    this.checked = true; 
    // or, to uncheck 
    this.checked = false; 
    // or, to toggle 
    this.checked = !this.checked; 
    });
    Copy after login

    注:在jQuery1.2及以上版本中,选择所有checkbox应该使用 input:checkbox , 因此以上代码第一行可写为:

    $(&#39;input:checkbox&#39;).each(function() {
    Copy after login

    无论何时候,当你的代码出现each时,你应该重写上面的代码来构造一个插件,很直接地:

    $.fn.check = function() { 
    return this.each(function() { 
    this.checked = true; 
    }); 
    };
    Copy after login

    这个插件现在可以这样用:

    $(&#39;input:checkbox&#39;).check();
    Copy after login

    注:在jQuery1.2及以上版本中,选择所有checkbox应该使用 input:checkbox 原文为:$("input[type='checkbox']").check();
    现在你应该还可以写出uncheck()和toggleCheck()了.但是先停一下,让我们的插件接收一些参数.

    $.fn.check = function(mode) { 
    var mode = mode || &#39;on&#39;; // if mode is undefined, use &#39;on&#39; as default 
    return this.each(function() { 
    switch(mode) { 
    case &#39;on&#39;: 
    this.checked = true; 
    break; 
    case &#39;off&#39;: 
    this.checked = false; 
    break; 
    case &#39;toggle&#39;: 
    this.checked = !this.checked; 
    break; 
    } 
    }); 
    };
    Copy after login

    这里我们设置了默认的参数,所以将"on"参数省略也是可以的,当然也可以加上"on","off", 或 "toggle",如:

    $("input[type=&#39;checkbox&#39;]").check(); 
    $("input[type=&#39;checkbox&#39;]").check(&#39;on&#39;); 
    $("input[type=&#39;checkbox&#39;]").check(&#39;off&#39;); 
    $("input[type=&#39;checkbox&#39;]").check(&#39;toggle&#39;);
    Copy after login

    如果有多于一个的参数设置会稍稍有点复杂,在使用时如果只想设置第二个参数,则要在第一个参数位置写入null.
    从上一章的tablesorter插件用法我们可以看到,既可以省略所有参数来使用或者通过一个 key/value 对来重新设置每个参数.
    作为一个练习,你可以试着为上面的例子实现的功能重写为一个插件.这个插件的骨架应该是像这样的:

    $.fn.rateMe = function(options) { 
    var container = this; // instead of selecting a static container with $("#rating"), we now use the jQuery context 
    var settings = { 
    url: "rate.php" 
    // put more defaults here 
    // remember to put a comma (",") after each pair, but not after the last one! 
    }; 
    if(options) { // check if options are present before extending the settings 
    $.extend(settings, options); 
    } 
    // ... 
    // rest of the code 
    // ... 
    return this; // if possible, return "this" to not break the chain 
    });
    Copy after login
  • 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