在输入聚焦时显示/隐藏div中的表格表行

tva*_*nt2 0 jquery

我正在使用注册表中的表,并希望<div class="collegeInfo">在输入id "profile_higher_ed"被聚焦时显示表中的行.我找到了一些答案就在这里像类似的问题这一个.但是当我调整jQuery时,当输入没有聚焦时,它并没有隐藏表行.

这是我的表单生成的HTML:

<tr>
  <td class="label"><label for="profile_higher_ed">College:</label></td>
  <td>
    <input id="profile_higher_ed" name="profile[higher_ed]" size="32" type="text" />
  </td>
</tr>
<div class="collegeInfo">
<tr>
  <td class="label"><label for="profile_major">Major:</label></td>
  <td>
    <input id="profile_major" name="profile[major]" size="32" type="text" />
  </td>
</tr>
<tr>
  <td class="label"><label for="profile_major">Grad Year:</label></td>
  <td class="select">
    <select id="date_year" name="date[year]">
      ...
      <option value="2011">2011</option>
    </select>
  </td>
</tr>
</div>
Run Code Online (Sandbox Code Playgroud)

这是我改编的jQuery:

$("#profile_higher_ed").focusin(function() {
    $("div.collegeInfo").show();
}).focusout(function () {
    $("div.collegeInfo").hide();
});
Run Code Online (Sandbox Code Playgroud)

那是我使用的问题<tr>之内<div>

And*_*iel 5

是的,<div>中间的<tr>元素是一个问题(它无效).我为你做了一个JS小提琴.如果我正确理解了这个问题,这就是你想要的:http://jsfiddle.net/cJRrx/5/

我在这两个<tr>元素上放了一个类,并改变了你的jQuery

$(document).ready(function(){
    $("tr.collegeInfo").hide();
});
$("#profile_higher_ed").focus(function() {
    $("tr.collegeInfo").show();
});
Run Code Online (Sandbox Code Playgroud)

编辑:您也可以尝试使用

$("#profile_higher_ed").live('focus', function() {
    $("tr.collegeInfo").show();
});
Run Code Online (Sandbox Code Playgroud)

要么

$("#profile_higher_ed").focusin(function() {
    $("tr.collegeInfo").show();
});
Run Code Online (Sandbox Code Playgroud)

作为焦点的替代方案,你可以做同样的事情.click().但是,由于您正在使用表单,如果用户选中它,这将没有多大帮助.

编辑2:正如评论中指出的那样,$("selector").on('focus', callback);现在使用起来更好,因为live()在jQuery中已经弃用了.