请运行我通过对this code执行基本上看toggleClass(函数(N)解释jQuery代码
$(document).ready(function(){
$("button").click(function(){
$("li").toggleClass(function(n){
return "listitem_" + n;
});
});
请运行我通过对this code执行基本上看toggleClass(函数(N)解释jQuery代码
$(document).ready(function(){
$("button").click(function(){
$("li").toggleClass(function(n){
return "listitem_" + n;
});
});
它等待,直到所有的HTML元素是从DOM,这是需要可靠地发现,在页面上的元素进行访问。这通常意味着页面的HTML代码首先必须加载(但不一定是图像)。 (Documentation for .ready
)
对于页面中的每个li
元件,一个函数被调用,该函数返回listitem_0
为第一个发现,listitem_1
用于第二,等等。 toggleClass
将从该元素中移除该已命名的类,如果它已经具有该元素,但是如果它尚未拥有它,则会添加它。
因此,该按钮充当了“切换开关”,它很可能在两个视觉上不同的外观(由页面的CSS代码定义)之间切换列表项。
发生了什么检查意见
// 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;
});
});
那么,从提供给toggleClass
的函数返回的类将在不存在时添加,如果它存在,则将其删除。
的n
参数是在节点列表中的元素的索引,所以第一个元件将具有"listitem_0"
类等等...
与ID“按钮”的元素被点击时 这个类listitem_ [0-9]被添加或从任何li元素中删除,取决于它是否已经拥有该类。
$(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;
});
});
对于每个是由于togglclass – aWebDeveloper 2010-11-26 08:00:14