代码之家  ›  专栏  ›  技术社区  ›  aWebDeveloper

解释jquery代码

  •  0
  • aWebDeveloper  · 技术社区  · 14 年前

    请告诉我执行死刑时发生了什么 this code 基本上看 toggleClass(函数(n)

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

    Complete code is here

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

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

    3. 为每个人 li 元素中,调用一个函数,该函数返回 listitem_0 第一次被发现, listitem_1 第二次,等等。 toggleClass 将从元素中移除已命名的类(如果它已拥有该类),但如果它尚未拥有该类,则将添加该类。

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

        2
  •  2
  •   Elzo Valugi    14 年前

    查看评论

    // 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;
            });
      });
    
        3
  •  1
  •   Jacob Relkin    14 年前

    好吧,从提供给 toggleClass 如果不存在,将被添加,如果存在,则将其删除。

    这个 n 参数是节点列表中元素的索引,因此第一个元素将具有 "listitem_0" 等等。。。

        4
  •  0
  •   austinbv    14 年前

    当点击ID为“button”的元素时 类listitem_u[0-9]是从任何li元素中添加或删除的,这取决于它是否已经拥有该类。

        5
  •  0
  •   Ali Tarhini    14 年前
       $(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; 
            }); 
          });