for循环中的jquery'Click'事件 [英] jquery 'click' event inside the for loop

查看:398
本文介绍了for循环中的jquery'Click'事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是javascript的新手。我想在javascript中执行像分页这样的任务。这是我的代码。

I am new to javascript. I want to do task like pagination in javascript.This is my code.

for(var i=1;i<=total_guest;i++)
{   
$("#Personal"+i).find("#Personal_details ").show();
$('#Personal'+i).find('.personal_info').click(function(e){
    alert(i);
        e.preventDefault();
        $("#Personal"+i).find("#Personal_details ").hide();


    }); 
}

说明:

在循环中,我得到total_guest值(例5)。在开始时我想获得第一位客人的页面。当我点击下一个按钮(class ='personal_info')时,我应该显示下一位客人的页面,如明智到第5位客人。

In loop i am getting total_guest value(example 5). At starting i want to get page for first guest.when i click next button(class='personal_info') i should show page for next guest like wise till 5th guest.

任何人都可以提供解决方案吗?

Can any one give solution?

编辑以包含HTML:

<div id='Personal1' > 
    <div id='Personal_details'> 
        <div class='personal_info'>button for next step</div> 
    </div> 
</div> 
<div id='Personal2' > 
    <div id='Personal_details'> 
        <div class='personal_info'>button for next step</div> 
    </div> 
</div>


推荐答案

要使循环工作,需要一个闭包在click函数中保持 i 的值不变,但这一切似乎都是不必要的,正如你所做的那样:

To make your loop work, you need a closure to keep the value of i constant inside the click function, but it all seems uneccessary, as you could just do:

$(".Personal_details").show().on('click', function(){
    $(this).hide();
}); 

请注意,ID是唯一的, .find(someID)没有意义,因为只有一个元素具有该ID。

Note that ID's are unique, and .find(someID) does'nt make sense, as there can be only one element with that ID.

编辑:基于新的HTML那是一个错误! 不能 两次(或更多次)使用相同的ID。

Based on the new HTML, that's an error! You can not have the same ID twice (or more).

<div id='Personal1' > 
    <div class='Personal_details'> 
        <div class='personal_info'>button for next step</div> 
    </div> 
</div> 
<div id='Personal2' > 
    <div class='Personal_details'> 
        <div class='personal_info'>button for next step</div> 
    </div> 
</div>

这篇关于for循环中的jquery'Click'事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆