【问题标题】:How do i select the nearest <input>?如何选择最近的 <input>?
【发布时间】:2017-08-29 06:55:37
【问题描述】:

我在输入字段的“内部”有一个图标。 当我悬停时,我希望更改图标及其所在输入字段的“类型”(我有 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",然后再返回。

【问题讨论】:

  • 不要随意将terms 放在code 样式when 他们aren't 代码中,这会损害可读性。
  • 也许 jQuery 的 .closest() 方法有帮助? api.jquery.com/closest

标签: jquery html css jquery-selectors selector


【解决方案1】:

试试这个小提琴路径https://jsfiddle.net/afckhbpo/

问题出在

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

这样使用:

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

【讨论】:

    【解决方案2】:

    就您标题中的问题而言,由于这些图标是紧随其相关字段的i 元素,因此$(this).prev() 将为您提供input 的jQuery 对象。

    因此,当我悬停图标时,它应该会更改并将输入字段的类型从“密码”更改为“文本”,然后再更改。

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

    【讨论】:

      猜你喜欢
      • 2021-05-02
      • 2020-03-09
      • 2011-05-04
      • 2021-10-02
      • 2011-10-24
      • 2016-06-08
      • 2014-09-17
      • 2017-03-19
      • 2018-04-02
      相关资源
      最近更新 更多