关于我的if-else语句,我在html文本更改事件上有一点问题。这是场景,我在下面有html布局,其中包含所有位置的下拉列表。现在,如果您在输入文本框中输入ID为“#searchloc”的位置,则会在您输入时查询并重新绑定“#dropdownlist”上的记录列表 div元素。所以我的问题是,我想将“#dropdownlist” div元素重新绑定到默认值,一旦我清除或清空“#searchloc”输入,它就会显示所有位置文本框但“#dropdownlist” div元素仍然清晰或空白。下面我尝试使用if-else语句来执行此操作,但我注意到在 else {...} 语句下,它不会触发函数甚至是警报方法。如何在jquery中处理这类问题?
HTML布局:
<input type="text" id="searchloc" class="searchloc" onchange = "QueryLocation();" onkeydown="this.onchange();" onkeyup="this.onchange();" onkeypress = "this.onchange();" oninput = "this.onchange();" placeholder="Search Location" />
<div id="dropdownlist" data-bind="foreach: PopulateAllLocation" >
<div id="alllocationdiv" > <label id="listlocation" class="listlocation" data-bind="text: CityTown"></label></div>
</div>
jQuery的:
// Change the dropdownlist result as text input change
function QueryLocation() {
if ($("#searchloc").val() != null) {
var dataObject = {
CityTown: $("#searchloc").val()
};
$.ajax({
url: '/OnlineStore/SearchLocation',
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: dataObject,
dataType: 'json',
success: function (data) {
self.PopulateAllLocation(data);
},
error: function () {
console.log('err')
}
});
}
else {
// Under this else statement won't fire any of this function...???
DisplayLocations();
alert("Textbox is empty...");
}
}
答案 0 :(得分:2)
当您在Javascript中检查空textbox
的值时,不是null
其""
,即空字符串。因此,在if
条件中,值永远不会等于null,这就是else
部分永远不会执行的原因。
function QueryLocation() {
if ($("#searchloc").val() != "") {
var dataObject = {
CityTown: $("#searchloc").val()
};
$.ajax({
url: '/OnlineStore/SearchLocation',
type: 'GET',
contentType: 'application/json; charset=utf-8',
data: dataObject,
dataType: 'json',
success: function (data) {
self.PopulateAllLocation(data);
},
error: function () {
console.log('err')
}
});
}
else {
DisplayLocations();
alert("Textbox is empty...");
}
}