gpt4 book ai didi

javascript - 如何根据变量的存在来更改 .keyup ?

转载 作者:行者123 更新时间:2023-12-03 09:57:23 25 4
gpt4 key购买 nike

我正在构建一个搜索表单,.keyup 中的 ajax 函数可以有不同的参数,我想通过检查是否存在另一个值来检查是否需要包含此参数。这是我现在拥有的:

var delay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();
if (GLOBAL_VARS['link_id']) {
search.keyup(function() {
delay(function() {
var query = search.val();
ajaxGet(GLOBAL_VARS.distributorsSearchDistUrl, {
'query': query,
'pk' : GLOBAL_VARS['link_id']
}, function(content) {
$('#distributors').html(content);
set_favorite();
});
}, 500);
});
} else {
search.keyup(function() {
delay(function() {
var query = search.val();
ajaxGet(GLOBAL_VARS.distributorsSearchDistUrl, {
'query': query
}, function(content) {
$('#distributors').html(content);
set_favorite();
});
}, 500);
});
}

HTML:

<div class="input-field col s6 right no-margin">
<input id="search" type="text" class="validate" name="search">
<label class="active" for="search">Search</label>
</div>

但是,在我输入任何字母(a 例如 get)后,这只有效 1 次:

search_dist?query=a&pk=64

但是当我输入 aa(第二个输入)时,我得到:

search_dist?query=aa

没有pk

我做错了什么?

enter image description here

最佳答案

对于初学者,我建议将您的条件放入 .keyup 回调中。这将避免尝试将同一事件两次绑定(bind)到同一元素的可能性。

search.keyup(function() {
delay(function() {
var data = {
query: search.val();
}
if (GLOBAL_VARS['link_id']) {
data.pk = GLOBAL_VARS.link_id;
}
ajaxGet(GLOBAL_VARS.distributorsSearchDistUrl, data, function(content) {
$('#distributors').html(content);
set_favorite();
});
}, 500);
});

工作中plnkr

关于javascript - 如何根据变量的存在来更改 .keyup ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30686802/

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