解释jquery代码

时间:2010-11-26 07:35:18

标签: jquery

请告诉我执行 this code时发生的事情基本上看 toggleClass(function(n)

   $(document).ready(function(){
      $("button").click(function(){
        $("li").toggleClass(function(n){
          return "listitem_" + n;
        });
      });

Complete code is here

5 个答案:

答案 0 :(得分:2)

检查评论

// when dom is loaded
$(document).ready(function(){
    // on somebody clicks a button element
    $("button").click(function(){
        // change the class of li elements in the page
        $("li").toggleClass(function(n){
            // with a value depending on the number of li element in 
            // the array of li elements
            return "listitem_" + n;
        });
  });

答案 1 :(得分:2)

  1. 它等待所有HTML元素都可以从DOM访问,这对于可靠地找到页面上的元素是必要的。这通常意味着首先必须加载页面的HTML代码(但不一定是图像)。 (Documentation for .ready

  2. 函数绑定到单击按钮时运行的所有button元素。 (jQuery.click

  3. 的文档
  4. 对于页面中的每个li元素,将调用一个函数,该函数返回listitem_0表示找到的第一个函数,listitem_1表示第二个,依此类推。 toggleClass将从元素中删除该命名类(如果它已经拥有它),但是如果它已经拥有它,它将添加它。

  5. 因此,该按钮充当“切换开关”,很可能在两个视觉上不同的外观之间切换列表项(由页面的CSS代码定义)。

答案 2 :(得分:1)

好吧,如果它不存在,那么从提供给toggleClass的函数返回的类将被添加,如果它存在则被删除。

n参数是节点列表中元素的索引,因此第一个元素的类为"listitem_0",依此类推......

答案 3 :(得分:0)

单击带有“按钮”ID的元素时 类listitem_ [0-9]在任何li元素中添加或删除,具体取决于它是否已经具有该类。

答案 4 :(得分:0)

   $(document).ready(function(){  // document load, ready to execute code
      $("button").click(function(){  // when all html elements that have a tag named 'button' is clicked
        $("li").toggleClass(function(n){ // change the class of all li elements in the page to the "listitem_" + the number of li elements on the page
          return "listitem_" + n; 
        }); 
      });