替换按钮不能工作

replaced Button wont work

本文关键字:工作 不能 按钮 替换      更新时间:2023-09-26

我有这个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

我想要的是:当我点击第二个功能时,我将返回按钮,因为它们是第一次。

我试图使这个第二个功能在第一个,但我得到的是功能工作,但只有一次,我的意思是,如果我再次点击重置密码将不起作用。

谢谢你的帮助

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

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

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

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