我有这段代码:
$(document).ready(function() {
$('#search').keyup(function() {
var search = $('#search').val();
console.log(search);
if (search.length !== 0 || search !== "") {
$('.wrapper').css({
"background-color": "#000",
"opacity": 0.8
});
$('.post').remove();
} else {
location.reload(false);
};
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#">
<button type="submit">Search</button>
<input type="text" name="search" id="search" />
</form>
但问题是无论在输入元素的开头放置空格,该函数都不起作用(它继续运行$('.wrapper').css({"background-color":"#000","opacity":0.8}); and $('.post').remove();
)。
答案 0 :(得分:1)
只需在条件之前添加search = search.trim();
。
当您向输入search
添加空格时,' '
不是''
,因此需要trim。
此外,使用:
if (search) {
....
}
而不是
if (search.length !== 0 || search !== '') {
...
}
在这种情况下,更简单的检查会给你相同的结果。 ''
和0
都是'falsey'。
$(document).ready(function() {
$('#search').keyup(function() {
var search = $('#search').val();
search = search.trim(); //Try adding this line
console.log(search);
if (search.length !== 0 || search !== "") {
$('.wrapper').css({
"background-color": "#000",
"opacity": 0.8
});
$('.post').remove();
} else {
location.reload(false);
};
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#">
<button type="submit">Search</button>
<input type="text" name="search" id="search" />
</form>
答案 1 :(得分:0)
使用String#trim
删除文字前后的空格:
var search = $('#search').val().trim();
$(document).ready(function() {
$('#search').keyup(function() {
var search = $('#search').val().trim();
if (search) {
$('.wrapper').css({
"background-color": "#000",
"opacity": 0.8
});
$('.post').remove();
} else {
location.reload(false);
};
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="#">
<button type="submit">Search</button>
<input type="text" name="search" id="search" />
</form>
答案 2 :(得分:0)
只需简单地使用!要么 !!检查空字符串:
con.Open();
SqlCommand cmd = new SqlCommand();
cmd = new SqlCommand("delete from tblImages where ID= @id", con);
cmd.Parameters.Add("@id", ddlDeleteHomeSlideImage.SelectedItem.ToString());
cmd.ExecuteNonQuery();
con.Close();