jQuery最近的();不工作 [英] jQuery closest(); not working

查看:79
本文介绍了jQuery最近的();不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当文本输入焦点对准时,我试图显示一些文本,但是最接近的();方法似乎不起作用.

I am trying to do make some text show when a text input is on focus, but the closest(); method doesn't seem to be working.

我已经完成了 JS小提琴供您查看.

I have done a JS Fiddle for you to look at.

这也是代码.

JS

$(document).ready(function(){
  $('.validation-error').hide();
  $('.name-input').on("focus", function(){
   $(this).closest('.validation-error').show();
  });
});

HTML

<fieldset>
 <legend>User Details</legend>
  <table>
   <tr>
    <td width="200">
     <label for="user"><span class="required-fields">*</span> User     Name</label>
    </td>
  <td>
    <input type="text" id="user" class="name-input">
  </td>
  <td>
   <p class="validation-error">This field cannot be blank or less than 2 characters.</p>
  </td>
 </tr>
 <tr>
  <td>
   <label for="job_title"><span class="required-fields">*</span> Job Title</label></td>
   <td>
    <input type="text" id="job_title" class="name-input">
   </td>
   <td>
    <p class="validation-error">This field cannot be blank or less than 2 characters.</p>
  </td>
 </tr>
 <tr>
  <td>
   <label for="full_name">* Full Name</label>
  </td>
  <td>
   <input type="text" id="full_name" class="name-input">
  </td>
  <td>
   <p class="validation-error">This field cannot be blank or less than 2 characters.</p>
  </td>
 </tr>
 </table>
</fieldset>

任何帮助将不胜感激.

推荐答案

.closest()查找最近的父元素, .validation-error不是name-input元素的父级.您需要.validation-error元素,该元素位于与输入元素相同的tr

.closest() finds the nearest parent element, .validation-error is not a parent of the name-input element. You need the .validation-error element which comes under the same tr as the input element

您需要

$(this).closest('tr').find('.validation-error').show();

$(this).closest('td').next().find('.validation-error').show();

这篇关于jQuery最近的();不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆