jQuery 最接近(); 不工作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17466981/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 19:09:46  来源:igfitidea点击:

jQuery closest(); not working

jquerytraversalclosest

提问by Ollie2619

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.

当文本输入处于焦点时,我试图做一些文本显示,但最接近();方法似乎不起作用。

I have done a JS Fiddlefor you to look at.

我已经做了一个JS Fiddle给你看。

and here is the code also.

这里也是代码。

JS

JS

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

HTML

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>

Any help would be appreciated.

任何帮助,将不胜感激。

回答by Arun P Johny

.closest()finds the nearest parent element, .validation-erroris not a parent of the name-inputelement. You need the .validation-errorelement which comes under the same tras the input element

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

You need

你需要

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

or

或者

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

回答by Olrac

Try my version Demo Fiddlealthough Arun P. Johny's answer is much better..

试试我的版本Demo Fiddle虽然 Arun P. Johny 的回答要好得多。

$(this).parent().siblings().find('.validation-error').show();