0

我有这个 html 表单

   <form action="" method="post" name="login_form">
     Email :  <input type="text" id="email2" name="email" /><br />
     <span id="passwordT" >Password : </span> 
     <input type="password" name="password" id="password2"/><br />
     <input type="button" id="submit_botton" value="Login" />
     <div><input id="forgot" type="button" value="Forgot your Password?" /></div>
  </form>

和这里的javascript

var forgot = $('#forgot');
var forgot2 = $('#forgot2');
forgot.click(function() {
   $('#password2').hide();
   $('span#passwordT').hide();
   $('input#submit_botton').prop('value', 'Reset Passowrd'); 
   $('input#forgot').replaceWith('<input id="forgot2" type="button" value="Login here" />');
});
$('input#forgot2').click(function() {        // this function didnt want to work
      $('input#forgot2').prop('value', 'Forgot your Password?');  
      $('#password2').show();
      $('span#passwordT').show();
      $('input#submit_botton').prop('value', 'Login'); 
 });

在这里 JS-DEMO

我想要的是:当我点击第二个功能时,我会像第一次一样找回按钮。

我试图在第一个函数中创建第二个函数,但我得到的是该函数有效但只有一次,我的意思是如果我再次单击以重置密码将不起作用。

谢谢您的帮助。

4

1 回答 1

8

您的问题是您试图将事件处理程序附加到尚不存在的元素。这对于直接事件处理程序是不可能的。请改用委托事件。

$(document).on('click','#forgot2', function(){ ... });

document可以替换#forgot2为绑定时存在的任何容器。

作为旁注,请注意,当您使用 id 选择器(例如#forgot2)时,不需要添加任何其他内容,因为 id 标识一个且仅标识一个元素(不允许重复的 id)。所以这个选择器input#forgot2没有错,但比必要的复杂。

于 2013-06-14T15:20:08.247 回答