<!DOCTYPE html><html lang="en"><head><meta charset="utf-8" /><script src="jquery-1.9.1.min.js" type="text/javascript"></script><script type="text/javascript" >$(function(){ var t = []; var dt = $("dl.collapse dt"); var dd = $("dl.collapse dd"); dt.each(function(i){ t[i] = false; $(dt[i]).click((function(i,dd){ return function(){ if( t[i]){ $(dd).show(); t[i] = false; } else{ $(dd).hide(); t[i] = true; } } })(i,dd[i])); })})</script><style type="text/css">.collapse { border:solid 1px #ccc; margin:2px; float:left; }.collapse dt { padding:8px 8px; background:#7FECAD url(green.gif) repeat-x; font-size:13px; font-weight:bold; color:#71790C; border-bottom:solid 1px #efefef; cursor:pointer; }.collapse dd { margin:0; padding:6px; }.w1 {width:310px;}.w2 {width:221px;}.w3 {width:665px;}</style><title>上机练习</title></head><body><dl class="collapse w1"> <dt>音乐标签</dt> <dd><img src="mp31.jpg" /></dd></dl><dl class="collapse w2"> <dt>新歌TOP100</dt> <dd><img src="mp32.jpg" /></dd></dl><dl class="collapse w3"> <dt>音乐掌门人</dt> <dd><img src="mp33.jpg" /></dd></dl></body></html>
$(dt[i]).click((function(i,dd){ return function(){ if( t[i]){ $(dd).show(); t[i] = false; } else{ $(dd).hide(); t[i] = true; } } })(i,dd[i]));
$(dt[i]).click((function(i,dd){ if( t[i]){ $(dd).show(); t[i] = false; } else{ $(dd).hide(); t[i] = true; } })(i,dd[i]));
Click binding must be a function. After you modify it, it will become a function that is automatically executed when it comes up. This is definitely wrong
And because of the problem of i scope, use Closure solves the i index problem, and finally returns the function to click
One is to pass the function, the one you wrote is executed directly, the difference is so big
After two people’s guidance, I already understand~thank you