使用JS隐藏标签

时间:2019-04-04 01:39:36

标签: javascript

点击后,我试图隐藏输入中的标签。

HTML

<form id="submit" method="get">
  <div class="md-form">
    <label for="getP">Search for Professor</label>
    <input class="tt-query form-control" 
           id="typeValue"
           spellcheck="false"
           autocomplete="off"
           name="getP"
           type="text"/>
  </div>
 <button class="btn btn-info btn-sm btn-block my-4 submit" type="submit">Submit</button>
 <hr>
</form>

我正在使用以下

  $(".form-control").focus(function() {
    $(this).prev("label").hide(); //hide label of clicked item 
  }).blur(function() {
    $(this).prev("label").show();
  });

尽管会触发,但它不会隐藏标签。

3 个答案:

答案 0 :(得分:0)

您提供的代码可以正常工作,如下所示。请检查错误,并确保已在控制台中正确添加了`jQuery exists: ${typeof jQuery !== 'undefined'}`的Jquery。

$(".form-control")
  .focus(function() {
    $(this).prev("label").hide(); //hide label of clicked item 
  })
  .blur(function() {
    $(this).prev("label").show();
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="submit" method="get">
  <div class="md-form">
    <label for="getP">Search for Professor</label>
    <input class="tt-query form-control" id="typeValue" spellcheck="false" autocomplete="off" name="getP" type="text" />
  </div>
  <button class="btn btn-info btn-sm btn-block my-4 submit" type="submit">Submit</button>
  <hr>
</form>

请注意,尽管用于切换标签的方法有效,但可以通过分配ID并切换焦点来更清晰地键入。

答案 1 :(得分:0)

我使用您的代码创建了一个fiddle,它可以正常工作。请检查是否包含了jQuery库。

$(".form-control").focus(function() {
    $(this).prev("label").hide(); //hide label of clicked item 
}).blur(function() {
    $(this).prev("label").show();
});

答案 2 :(得分:0)

jQuery show / hide用于none / block显示。 您会不会混淆可见/不可见的原理?

PS:for标签中的<label>属性引用的是Id,而不是name

$(".form-control") 
  .focus(function () {
    $(this).prev("label").css('visibility', 'hidden');
    // $(this).prev("label").hide(); //hide label of clicked item 
  })
  .blur(function () {
    $(this).prev("label").css('visibility', 'visible');
    // $(this).prev("label").show();
  });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="submit" method="get">
  <div class="md-form">
    <label for="typeValue">Search for Professor</label>
    <input class="tt-query form-control" id="typeValue" spellcheck="false" autocomplete="off" name="getP"
      type="text" />

  </div>
  <button class="btn btn-info btn-sm btn-block my-4 submit" type="submit">Submit</button>
  <hr>
</form>