Rumah > Artikel > hujung hadapan web > for遍历添加点击事件,但是每个按钮只能添加最后一个地址_html/css_WEB-ITnose
for遍历添加给每一个a标签添加点击事件,给每一个a标签添加地址,但是遍历后每一个按钮只添加最后一个地址
<div id="navbar" class="navbar-collapse collapse"> <ul class="nav navbar-nav"> <li><a href="javascript:;">登录</a></li> <li><a href="javascript:;">注册</a></li> <li><a href="javascript:;">写点评</a></li> <li><a href="javascript:;">服务中心</a></li> </ul> <ul class="nav navbar-nav navbar-right"> <li class="dropdown"> <a href="javascript:;" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">广州<span class="caret"></span></a> <ul class="dropdown-menu"> <li><a href="javascript:;"><center>城市(国内)</center></a></li> <li><a href="javascript:;"><center>省份(国内)</center></a></li> <li><a href="javascript:;"><center>港台</center></a></li> <li role="separator" class="divider"></li> <li><a href="javascript:;"><center>城市(国外)</center></a></li> <li><a href="javascript:;"><center>省份(国外)</center></a></li> <li><a href="javascript:;"><center>更多...</center></a></li> </ul> </li> </div>
var redirect = function(){ var menusHrefs=[ '/login/loginIndex', '/register/registerIndex', '/register/registerIndex', '/register/registerIndex', '/location/getCityInChina' ]; //获取导航栏全部a标签 var lab = $('#navbar ul').children().filter('li').children().filter('a').not($('#navbar ul').children().filter('li').children().filter('.dropdown-toggle')); for(var x=0 ; x<menusHrefs.length ; x++){ for(var x in menusHrefs){ $(lab[x]).on('click',function(){ window.location.href = menusHrefs[x]; }) }}();
事件执行时,for循环早就结束了,这个时候x已经是最大值加1了。
var redirect = function(){ var menusHrefs=[ '/login/loginIndex', '/register/registerIndex', '/register/registerIndex', '/register/registerIndex', '/location/getCityInChina' ]; //获取导航栏全部a标签 var lab = $('#navbar ul').children().filter('li').children().filter('a').not($('#navbar ul').children().filter('li').children().filter('.dropdown-toggle')); lab.on('click',function(event){ window.location.href = menusHrefs[lab.index(this)]; event.preventDefault(); })}();