2013-05-09 46 views
0

在登录框中,我添加了一个名为“重置密码”的按钮。点击该按钮时,我会在同一表单中显示更多字段,按钮显示“取消”。但是当点击“取消”并且添加字段消失时,原始按钮将停止连续点击。jquery - 在另一个点击内添加的点击事件阻止了原始点击

<div class="show_hide_login_box margin10-right"> 
    <dl> <dt>Username:</dt> 

     <dd> 
      <input type="text" class="input" value="[email protected]" name="company_user[username]" readonly="true"><span style="display:none;">@xento</span> 
     </dd> 
    </dl> 
    <dl id="passward_link" style="display: block;"> <dt>Password:</dt> 

     <dd> 
      <input type="text" class="input" value="[email protected]" name="company_user[username]" readonly="true"><span style="display:none;">@xento</span> 
     </dd> 
    </dl> 
    <div id="password_fields" style="display: none;"> 
     <dl> <dt>Current Password:</dt> 

      <dd> 
       <input type="password" class="input"> 
      </dd> 
     </dl> 
     <dl> <dt>New Password:</dt> 

      <dd> 
       <input type="password" class="input"> 
      </dd> 
     </dl> 
     <dl> <dt>Verify New Password:</dt> 

      <dd> 
       <input type="password" class="input"> 
      </dd> 
     </dl> 
     <dl> <dt></dt> 

      <dd><small>Passwords must be at least 6 characters long</small> 
      </dd> 
     </dl> 
    </div> 
    <hr> 
    <dl> <dt>&nbsp;</dt> 

     <dd> 
      <button class="button">Login</button> 
      <button class="button reset_pass">Reset Password</button> 
     </dd> 
    </dl> 
</div> 

和JS代码

$(document).ready(function() { 

/* SHOW-HIDE LOGIN BOX */ 

$('.reset_pass').on('click',function(){ 
    $('#password_fields').show(); 
    $(this).text('Cansel'); 
    $(this).addClass('cansel_box'); 
    $('.cansel_box').on('click',function() { 
     $('#password_fields').hide(); 
     $(this).text('Reset Password'); 
     $(this).removeClass('cansel_box'); 
    }); 
}); 
}); 

这里运行示例:http://jsfiddle.net/eKGbL/1/

我必须做一些根本性的错误在这里。

+1

是,附加的事件处理程序中的事件处理程序,在大多数情况下根本不对! – adeneo 2013-05-09 10:20:46

回答

2

这是因为,要附加几个点击处理程序将一个元件,其实你应该委托的事件,但我建议toggle方法:

$('.reset_pass').on('click', function() { 
    $('#password_fields').toggle(); 
    $(this).text(function(_, oldText){ 
     return oldText === 'Reset Password' ? 'Cancel' : 'Reset Password'; 
    }); 
}); 

http://jsfiddle.net/6TwYH/

+2

+1这是完美的工作 – PSR 2013-05-09 10:21:42