2013-01-07 46 views
1

我有一個表格以下輸入:使用Javascript/jQuery的不模糊工作

<input class="password" type="password" title="Your Password" name="password" size="30" autocomplete="off" value="" > 

<input class="confirmpass" type="password" title="Confirm Password" name="pass_confirm" size="30" autocomplete="off" value="" > 
    <div class="jresults" align="left" style="display:none;" id="confirmdata"></div> 

    <input class="showpassword" type="checkbox" title="Show Passwords"> 

這是顯示密碼功能:

//Show password function 
$(".showpassword").click(function() 
    { 
    var change = $(this).is(":checked") ? "text" : "password"; 
    var password = $("input.password"); 
    var showpass = $("<input type='" + change + "' />") 
       .attr("id", password.attr("id")) 
       .attr("title", password.attr("title")) 
       .attr("name", password.attr("name")) 
       .attr("size", password.attr("size")) 
       .attr('class', password.attr('class')) 
       .val(password.val()) 
       .insertBefore(password); 
      password.remove(); 
      password = showpass; 
    var confirmpass = $("input.confirmpass"); 
    var showconfirm = $("<input type='" + change + "' />") 
       .attr("id", confirmpass.attr("id")) 
       .attr("title", confirmpass.attr("title")) 
       .attr("name", confirmpass.attr("name")) 
       .attr("size", confirmpass.attr("size")) 
       .attr('class',confirmpass.attr('class')) 
       .val(confirmpass.val()) 
       .insertBefore(confirmpass); 
      confirmpass.remove(); 
      confirmpass = showconfirm;  
    }); 

這是確認密碼匹配功能:

//match passwords entered 
$('.confirmpass').blur(function() 
    { 
    var Pass = $('.password').val(); 
    var cPass = $('.confirmpass').val(); 
    $('#confirmdata').css("display","none"); 
    if(cPass.length>5) 
     { 
     if (Pass != cPass) 
      { 
       $('#confirmdata').css("display","block"); 
       $('#confirmdata').css("color","#ff0000"); 
       $('#confirmdata').html("No Match"); 
       $("input.confirmpass").focus(); 
      return; 
      } 
     $('#confirmdata').css("display","block"); 
     $('#confirmdata').css("color","#00BB00"); 
     $('#confirmdata').html("Matched"); 
    } 
    }); 

問題:

如果密碼不匹配,我改正,對模糊的確認密碼將再次如預期運行..... 這是正確的

現在,如果做密碼不匹配,我點擊複選框顯示密碼,然後更正,確認密碼將不是再次運行模糊。

任何人都可以看到什麼可能導致此?

+0

您將要從DOM這也將刪除與它相連的事件處理程序的元素替換函數聲明

$('.confirmpass').blur(function() 

(顯然)。現在,增加了新的元素沒有這個事件處理程序綁定。我相信這可以很容易地通過使用事件委託來解決 – Alexander

回答

3

當點擊複選框時,您將動態內容插入頁面,這就是爲什麼之後模糊不起作用的原因。與

$(document).on('blur', '.confirmpass', function() 
+0

這些功能已經在文檔就緒功能中。這會有所作爲嗎?還是我需要自行打破證明?謝謝你的快速反應。 –

+0

查看下面Alexander的答案,當你從文檔中刪除元素時,他們的處理程序也會被刪除,之後你會重新添加它們,但處理程序會丟失。 'on()'方法自動將處理程序附加到現在和未來的元素,而blur()僅將處理程序附加到現有元素。 – AlecTMH

+0

這工作,謝謝。我會接受你的回答。 –