gpt4 book ai didi

jquery - 如何使用 jQuery 在输入的 keyup 上从特定的 div 添加/删除类?

转载 作者:太空宇宙 更新时间:2023-11-04 01:06:39 25 4
gpt4 key购买 nike

我希望每次有人开始在以下输入中键入文本时,将类“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>

最佳答案

问题是你的逻辑是从后到前的;您只需要在元素为空 (!==) 而不是 (==) 时应用该类:

$('#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 条件语句,如果 val() 为空,它会调用 removeClass(),或者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>

关于jquery - 如何使用 jQuery 在输入的 keyup 上从特定的 div 添加/删除类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52029995/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com