如何使用jQuery在输入键上添加/删除特定div中的类?

时间:2018-08-26 20:26:01

标签: jquery html css

我希望每次有人在以下输入中开始输入文本时,将类“ hideme”添加到具有id(btn1)的div中,并且在清理/清空字段时删除类“ hideme”并再次显示div 。

现在,如果您尝试在输入字段中键入内容,它将无法正常工作。

这是我的代码:

$('#price').on('keyup', function(){
  $("#btn1").toggleClass('hideme', $('#price').val()==''); 
})
#btn1 {
  background: #0088cc;
  color: #ffffff;
  width: auto;
  text-align: center;
  font-weight: bold;
  height: 48px;
  line-height: 48px;
  cursor: pointer;
  display: inline-block;
  font-size: 1em;
  margin-left: 10px;
  position: absolute;
  left: 220px;
  top: 8px;
  padding-left:10px;
  padding-right:10px;
}

#price {
  height:43px;
  line-height:43px;
  font-weight:bold;
  color:#585858;
  display:inline-block;
  font-size:1em;
}

.hideme {
  display:none!important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input autocomplete="off" id="price" placeholder="Enter Product Price"/> 
<div id="btn1">
  HEY I AM A NICE BUTTON
</div>

1 个答案:

答案 0 :(得分:2)

问题是您的逻辑背对背;您只需在元素为空(!==而不是(==)为空的情况下应用该类:

$('#price').on('keyup', function() {
  $("#btn1").toggleClass('hideme', $('#price').val() !== '');
})
#btn1 {
  background: #0088cc;
  color: #ffffff;
  width: auto;
  text-align: center;
  font-weight: bold;
  height: 48px;
  line-height: 48px;
  cursor: pointer;
  display: inline-block;
  font-size: 1em;
  margin-left: 10px;
  position: absolute;
  left: 220px;
  top: 8px;
  padding-left: 10px;
  padding-right: 10px;
}

#price {
  height: 43px;
  line-height: 43px;
  font-weight: bold;
  color: #585858;
  display: inline-block;
  font-size: 1em;
}

.hideme {
  display: none!important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input autocomplete="off" id="price" placeholder="Enter Product Price" />
<div id="btn1">
  HEY I AM A NICE BUTTON
</div>

但是,我建议使用一个简单的if条件,如果removeClass()为空,则调用val(),如果else则调用addClass()值已填充。

这使事情变得更加清晰,可以在下面看到:

$('#price').on('keyup', function() {
  if ($('#price').val() == '') {
    $("#btn1").removeClass('hideme');
  } else {
    $("#btn1").addClass('hideme');
  }
})
#btn1 {
  background: #0088cc;
  color: #ffffff;
  width: auto;
  text-align: center;
  font-weight: bold;
  height: 48px;
  line-height: 48px;
  cursor: pointer;
  display: inline-block;
  font-size: 1em;
  margin-left: 10px;
  position: absolute;
  left: 220px;
  top: 8px;
  padding-left: 10px;
  padding-right: 10px;
}

#price {
  height: 43px;
  line-height: 43px;
  font-weight: bold;
  color: #585858;
  display: inline-block;
  font-size: 1em;
}

.hideme {
  display: none!important;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input autocomplete="off" id="price" placeholder="Enter Product Price" />
<div id="btn1">
  HEY I AM A NICE BUTTON
</div>