请告诉我执行 this code时发生的事情基本上看 toggleClass(function(n)
$(document).ready(function(){
$("button").click(function(){
$("li").toggleClass(function(n){
return "listitem_" + n;
});
});
答案 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)
它等待所有HTML元素都可以从DOM访问,这对于可靠地找到页面上的元素是必要的。这通常意味着首先必须加载页面的HTML代码(但不一定是图像)。 (Documentation for .ready
)
对于页面中的每个li
元素,将调用一个函数,该函数返回listitem_0
表示找到的第一个函数,listitem_1
表示第二个,依此类推。 toggleClass
将从元素中删除该命名类(如果它已经拥有它),但是如果它已经拥有它,它将添加它。
因此,该按钮充当“切换开关”,很可能在两个视觉上不同的外观之间切换列表项(由页面的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;
});
});