2014-12-05 61 views
0

我有一個顯示/隱藏密碼按鈕,當我單擊以顯示密碼時,它的工作原理,但是當我嘗試再次隱藏它時,它不會。更改元素ID後無法觸發操作

小提琴:http://jsfiddle.net/vcvgj09z/

<input type="password" id="pass1" value="Now try to hide me"> 
<a href="#" id="show-password"><i class="fa fa-eye"></i> Show</a> 

    $("#show-password").on("click",function() { 
     $(this).html('<i class="fa fa-eye-slash"></i> Hide'); 
     $(this).prop("id","hide-password"); 
     $("#pass1").attr("type","text"); 
    }); 
    $("#hide-password").on("click",function() { 
     $(this).html('<i class="fa fa-eye"></i> Show'); 
     $(this).prop("id","show-password"); 
     $("#pass1").attr("type","password"); 
    }); 
+1

不要更改元素的ID ... – 2014-12-05 17:08:21

+0

試圖刪除/ addClass太:( – 2014-12-05 17:08:44

+1

在你的代碼中的點擊事件時運行的約束 - 和在運行時'#hide-password'不存在 – Terry 2014-12-05 17:08:59

回答

4

按我的意見,爲什麼你的代碼是不工作的原因是因爲該元素#hide-password不存在在運行時的DOM,所以沒有點擊事件將被綁定到它

儘管您可以使用.on()來偵聽事件冒泡,但我強烈建議不要更改元素的ID。相反,您可以將切換開關狀態存儲爲jQuery data對象。這種方法的優點是:

  • 不依賴於改變標記和事件通過評估和修改的jQuery data對象
  • 允許其它元件來操縱鼓泡
  • 存儲密碼的切換狀態/影響切換狀態

見小提琴這裏:http://jsfiddle.net/teddyrised/vcvgj09z/10/

$('#toggle-password').click(function() { 
    // Check state 
    if(!$(this).data('state') || $(this).data('state') == 0) { 
     // If the data object "state" is undefined or have a value of 0, convert password to text 
     // Update HTML and data object 
     $(this) 
     .html('<i class="fa fa-eye-slash"></i> Hide') 
     .data('state', 1); 

     // Change password to text 
     $("#pass1").attr('type', 'text'); 
    } else { 
     // If the data object "state" has a value of 1, convert text to password 
     // Update HTML and data object 
     $(this) 
     .html('<i class="fa fa-eye"></i> Show') 
     .data('state', 0); 

     // Change text to password 
     $("#pass1").attr("type","password"); 
    } 
}); 
+0

感謝您分享您的知識!非常具有啓發性 – 2014-12-05 17:20:16

3

嘗試這樣的事情...

$("body").on("click", "#show-password", function() { 

...和...相關

$("body").on("click", "#hide-password", function() { 

這樣,當ID動態變化,點擊即可使用。

+0

感謝哥們,它工作。我明白爲什麼它不起作用,正如特里所說。 – 2014-12-05 17:10:42

0

您應該使用委託。因爲你產生新的DOM

$(document).on("click","#show-password",function() { 
    //.... 
}); 
$(document).on("click","#hide-password",function() { 
    //.... 
}); 
2

您的代碼不起作用,因爲它不支持動態設置的元素。

爲動態添加的元素設置事件的正確方法是使用$(document).on()

JS:

$(document).on("click", "#show-password", function() { 
    $(this).html('<i class="fa fa-eye-slash"></i> Hide'); 
    $(this).prop("id","hide-password"); 
    $("#pass1").attr("type","text"); 
}); 

$(document).on("click", "#hide-password", function() { 
    $(this).html('<i class="fa fa-eye"></i> Show'); 
    $(this).prop("id","show-password"); 
    $("#pass1").attr("type","password"); 
}); 

Updated jsFiddle

+0

感謝哥們,明白了! – 2014-12-05 17:22:05