我如何 select 最近的 <input>?

How do i select the nearest <input>?

我有一个输入框图标 'inside'。 当我悬停时,我希望图标发生变化,并且输入字段的 "type" 位于其中(我有 3 个这样的字段,所以我想 select 这个特定的字段)

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(只是为了理解 "inside" 的意思):

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

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

因此,当我将鼠标悬停在图标上时,它应该会发生变化,并将输入字段的类型从 "password" 更改为 "text",然后再更改回来。

就您标题中的问题而言,由于这些图标是 i 元素,紧跟在它们相关的字段之后,$(this).prev() 会给您一个 jQuery object 对于 input.

So when I hover the icon it should change and change the type of my input field from "password" to "text" and back later on.

一旦 input 创建并具有类型,您就无法更改该类型(spec allows it,但某些浏览器 [还] 不处理它)。相反,您可以有两个输入(一个 type="text",另一个 type="password"),并根据需要 show/hide。

试试这个 fiddle 路径 https://jsfiddle.net/afckhbpo/

问题出在

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

这样使用:

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