我希望如果我的输入文本值不是空的,那么显示我的.removetext
div,但它不能正常工作。如果在第二个字符后键入某个内容,则我的.removetext
将被隐藏,但如果我的输入不为空,则不要隐藏我的.removetext
类。
我的错误在哪里?我想我不明白按键事件
$(document).ready(function() {
$('.search-hotels').on('input', function() {
var val = $.trim(this.value);
if (!val == "") {
$(".removetext").show(val.length > 0, function() {
var clear = $(this);
clear.on('click', function() {
alert('hey');
})
});
} else {
$(".removetext").hide();
}
});
});
.main {
position: relative;
width: 40%;
}
.search-hotels {
width: 100%;
padding: 15px;
border: 3px solid #ccc;
}
.removetext {
position: absolute;
right: 0;
top: 25%;
font-size: 23px;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
<input type="text" class="search-hotels">
<div class="removetext">×</div>
</div>
最佳答案
尝试输入-它也处理粘贴:
$(function() {
$('.search-hotels').on('input', function() {
var val = $.trim(this.value);
$(".removetext").toggle(val.length>0); // test anything not blank
});
// the event handler needs to be HERE and not inside the inout handler
$(".removetext").on('click', function() {
alert('hey');
});
});
.main {
position: relative;
width: 40%;
}
.search-hotels {
width: 100%;
padding: 15px;
border: 3px solid #ccc;
}
.removetext {
position: absolute;
right: 0;
top: 25%;
font-size: 23px;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
<input type="text" class="search-hotels" value="">
<div class="removetext">×</div>
</div>
如果你需要回拨,你需要显示和隐藏
$(function() {
$('.search-hotels').on('input', function() {
var show = $.trim(this.value).length>0;
if (show) {
$(".removetext").show("slow",function() {
console.log("showing");
});
}
else {
$(".removetext").hide("slow",function() {
console.log("hiding");
});
}
});
});
.main {
position: relative;
width: 40%;
}
.search-hotels {
width: 100%;
padding: 15px;
border: 3px solid #ccc;
}
.removetext {
position: absolute;
right: 0;
top: 25%;
font-size: 23px;
display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
<input type="text" class="search-hotels" value="">
<div class="removetext">×</div>
</div>