我正在同時使用 Keyup & change Both 并且它作業正常,沒有任何問題,但問題只是當用戶停止鍵入并單擊頁面主體上的任意位置時,ajax 再次運行。
問題出在哪里,請任何人幫助我,下面是我的代碼
$(".eventclass").on('keyup change', function (){
var txt = $('#search_text').val();
var st = $('input[type=radio]:checked', '.radiostatus').val();
var act_id = $('.actid').val();
var child_id = $('.childid').val();
if(txt != '' || st !='' || act_id !='' || child_id !='')
{
$('#maindiv').hide();
$("#loadi").show();
if (globalTimeout != null) {
clearTimeout(globalTimeout);
}
globalTimeout = setTimeout(function() {
globalTimeout = null;
$.ajax({
url:"activity_post_load.php",
method:"post",
data:{
search:txt,
status: st,
actid: act_id,
childid: child_id
},
dataType:"text",
success:function(data)
{
setTimeout(function() {
$("#loadi").hide();
$('#results').html(data);
}, 1000);
}
});
}, 2000);
}else{
$('#results').html('');
$('#maindiv').show();
}
});
這是頁面的HTML以便更好地理解,我正在使用輸入和選擇
<div class="row fx-wrap">
<div class="form-group col-xs-12 col-sm-5 col-md-6">
<label class="form-label"> Search Posts</label>
<input type="text" name="keysearch" id="search_text"
placeholder="Search by sightseeing Name" class="form-control
eventclass" placeholder="Search Sightseeing places" />
</div>
<div class="form-group col-xs-12 col-sm-2 col-md-2">
<label class="form-label"> Act_id </label>
<select name="act_id" class="form-control actid eventclass">
<option value="">PARENT</option>
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
</div>
<div class="form-group col-xs-12 col-sm-2 col-md-2">
<label class="form-label"> Child_id </label>
<select name="child_id" class="form-control childid eventclass">
<option value="">CHILD</option>
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
</div>
<div >
<div >
All <input type="radio" name="stat"
value="all"><br>
Status 0 <input type="radio" name="stat"
value="zero"> <br>
Status 1 <input type="radio" name="stat"
value="1">
</div>
</div>
</div>
<div id="maindiv"></div>
uj5u.com熱心網友回復:
此行為是由change
事件在input
(或textarea
)元素上的作業方式引起的。
Mozilla 貢獻者解釋如下:
根據要更改的元素型別以及用戶與元素互動的方式,
change
事件會在不同的時刻觸發:[...] 4. 當元素在其值更改后失去焦點但未提交時
當您單擊頁面上的任意位置時會發生這種情況:此時,在input
元素中進行的“未提交”更改被提交,并且change
事件觸發。
input
您可以通過偵聽事件而不是事件來更改此行為change
。當你這樣做時,你不需要再聽keyup
事件了。所以:
$(".eventclass").on('input', function () {
// ... rest of code ...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/498254.html