jquery - 我如何选择最近的 <input>?

标签 jquery html css jquery-selectors selector

我在输入字段的“内部”有一个图标。 当我悬停时,我希望更改图标以及它所在的输入字段的“类型”(我有 3 个这样的字段,所以我想选择这个特定的字段)

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(只是为了理解“内部”指的是什么):

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

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

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

最佳答案

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

问题出在

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

像这样使用:

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

关于jquery - 我如何选择最近的 &lt;input&gt;?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43201045/

相关文章:

html - 如何在 CSS 中制作带 Angular 箭头?

css - 帮助将图像添加到下拉菜单

html - 我的带有 animated.css 的 html/css 元素中没有动画

jquery - 动态添加多个选定值并计算总计

php - 拉维尔 5 : How to Paginate an Ajax Response

使用 html5 选择器时不应用 CSS 样式。浏览器在渲染 CSS 方面有什么变化吗?

html - 制作此布局(CSS 或表格)的最佳方式是什么?

javascript - 在 Jquery 中创建词汇表字母表

javascript - 使用jquery突出显示具有最小值的html列

javascript - 如何将多选的值放入 echo 语句中?