取代按钮不会工作

ech*_*_Me 0 html javascript jquery

我有这个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>
Run Code Online (Sandbox Code Playgroud)

和这里的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'); 
 });
Run Code Online (Sandbox Code Playgroud)

这里是JS-DEMO

我想要的是:当我点击第二个功能时,我会在第一时间取回按钮.

我试图在第一个内部制作第二个功能,但我得到的是功能有效,但只有一次,我的意思是,如果我再次点击重置密码将无法正常工作.

谢谢您的帮助.

Cla*_*edi 8

您的问题是您正在尝试将事件处理程序附加到尚不存在的元素.使用直接事件处理程序是不可能的.请改用委托事件.

$(document).on('click','#forgot2', function(){ ... });
Run Code Online (Sandbox Code Playgroud)

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

作为附注,考虑到当你通过id(例如#forgot2)使用选择器时,没有必要添加任何其他东西,因为id识别一个而只是一个元素(不允许重复的id).所以这个选择器input#forgot2没有错,但比必要的更复杂.