2017-04-04 29 views
0

我有一個輸入欄內的圖標。 當我懸停,我想改變圖標和它在哪裏的內部的輸入字段的「類型」(我有3個字段這樣,所以要選擇此特定的一個)我如何選擇最近的<input>?

HTML:

<div class="change_subtitle">Enter Password</div> 
<input id="pw_old" class="change_input" type="text"><i class="fa fa-eye-slash" aria-hidden="true"></i></input> 
<div class="change_subtitle">Enter new Password</div> 
<input id="pw_new1" class="change_input" type="password"><i class="fa fa-eye-slash" aria-hidden="true"></i></input> 
<div class="change_subtitle">Confirm new Password</div> 
<input id="pw_new2" class="change_input" type="password"><i class="fa fa-eye-slash" aria-hidden="true"></i></input> 
<div class="button_confirm" onclick="inputIsValid()">Confirm</div> 

的jQuery:

$(".fa-eye-slash").hover(function(){ 
        if($(this).hasClass('fa-eye-slash')) { 
         $(this).removeClass('fa-eye-slash'); 
         $(this).addClass('fa-eye'); 
         $(this).attr('type' = 'text'); // I want to select the input here and change the type of it 
        } else if($(this).hasClass('fa-eye')) { 
         $(this).removeClass('fa-eye'); 
         $(this).addClass('fa-eye-slash'); 
         $(this).attr('type' = 'password'); // I want to select the input here and change the type of it back 
        } 
       }) 

CSS(剛剛明白了什麼是 「內部」 MENT):

.fa-eye-slash{ 
    color: #34495e; 
    margin-left: -20px; 
} 

.fa-eye{ 
    color: #34495e; 
    margin-left: -20px; 
} 

因此,當我將鼠標懸停在圖標上時,它應該更改並將我的輸入字段的類型從"password"改爲"text",稍後再回來。

+1

不要隨意把'terms'在'code'風格'when'他們''不''代碼,它削弱了可讀性。 –

+0

也許jQuery的.closest()方法可以提供幫助嗎? https://api.jquery.com/closest/ –

回答

1

試試這個小提琴路徑https://jsfiddle.net/afckhbpo/

問題是

$(this).attr('type' = 'text') 

使用這樣的:

$(this).prev().attr('type', 'text') 
0

根據標題中的問題,由於這些圖標是i元素,它們緊跟着它們相關的字段,因此$(this).prev()會爲您提供input的jQuery對象。

因此,當我將鼠標懸停在圖標上時,它應該改變並將我的輸入字段的類型從「密碼」更改爲「文本」,稍後再回來。

一旦input被創建並有一個類型,你不能改變的類型(spec allows it但有些瀏覽器不處理它[但])。相反,您可以有兩個輸入(一個type="text",另一個type="password"),並根據需要顯示/隱藏它們。