关于JS for循环问题~求解~~

qq_33278881 2016-09-23 10:30:09


如图~~求教该如何改进代码~才能达到点击按钮1输出1,点击按钮2输出2....这种效果~~万分感谢~~
...全文
236 7 打赏 收藏 转发到动态 举报
写回复
用AI写文章
7 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq_35683066 2016-09-24
  • 打赏
  • 举报
回复
1. 使用index()+1 2. 使用on 事件代理 绑定在 body 上
  • 打赏
  • 举报
回复
引用 2 楼 u011376884 的回复:

$(function(){
        $("button").click(function(){
                console.log($(this).index()+1);
        });
});
为什么还要循环
木头海上漂 2016-09-23
  • 打赏
  • 举报
回复
获取index值就可以了不需要循环绑的
cocotsau 2016-09-23
  • 打赏
  • 举报
回复
给一组节点加上相同的事件,相对于ID用类选择器是更好的选择。另外因为在低版本的JS中并没有块级作用域,所以不推荐使用for循环来给一组节点加事件

<button class="btn">按钮1</button>
<button class="btn">按钮2</button>
<button class="btn">按钮3</button>
<button class="btn">按钮4</button>
<button class="btn">按钮5</button>
<script type="text/javascript" src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script>
<script type="text/javascript">
$(".btn").click(function(){
	var index = $(this).prevAll().size();
	console.log(index+1);
})
</script>
  • 打赏
  • 举报
回复

$(function(){
        $("button").click(function(){
                console.log($(this).index()+1);
        });
});
为什么还要循环
its_good 2016-09-23
  • 打赏
  • 举报
回复
引用 1 楼 showbo 的回复:
闭包 $('#btn'+i).click((function(i){return function(){console.log(i)}})(i));
+1 正解 自己先消化下:

for(var i = 1; i <= 5; i++){
	document.getElementById("btn"+i).onclick = showinfo(i);
}
//closure
function showinfo(i){
	return function(){
		document.getElementById("test").innerHTML = "click" + i; 
	}
}
元素可以自定义属性,可以把相关的信息放到属性中; 如果只是显示button的序号, index() 就足够 index() 方法返回指定元素相对于其他指定元素的 index 位置 参考:http://www.w3school.com.cn/jquery/dom_element_methods_index.asp
Go 旅城通票 2016-09-23
  • 打赏
  • 举报
回复
闭包 $('#btn'+i).click((function(i){return function(){console.log(i)}})(i));

87,910

社区成员

发帖
与我相关
我的任务
社区描述
Web 开发 JavaScript
社区管理员
  • JavaScript
  • 无·法
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧