使用Jquery选择元素之后的元素位置

时间:2019-05-26 16:26:26

标签: jquery

我有以下HTML代码:

<input type="password" name="USR_NewPassword" class="form-control" maxlength="50" required>
<span class="input-group-addon">
    <a href=""><i class="fa fa-eye"></i></a>
</span>

如果我想单击<a>元素,为什么这不起作用?

$('input[name="USR_NewPassword"] span > a').on('click', function(event) {
   ...
});

2 个答案:

答案 0 :(得分:1)

只是缺少+

$('input[name="USR_NewPassword"] + span > a').on('click', function(event) {
  alert();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="password" name="USR_NewPassword" class="form-control" maxlength="50" required>
<span class="input-group-addon">
    <a href="#"><i class="fa fa-eye">icon</i></a>
</span>

答案 1 :(得分:0)

您的选择是错误的。将nextfind一起使用。

$('input[name="USR_NewPassword"]').next('span').find('a').on('click', function(event) {
  alert();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="password" name="USR_NewPassword" class="form-control" maxlength="50" required>
<span class="input-group-addon">
    <a href="#"><i class="fa fa-eye">icon</i></a>
</span>