Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
164 views
in Technique[技术] by (71.8m points)

traversal - jQuery closest(); not working

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 Fiddle for you to look at.

and here is the code also.

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>

Any help would be appreciated.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

.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

You need

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

or

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...