在 jquery ui 自动完成中将输入 ID 传递给 url
Pass input id to url in jquery ui autocomplete
我需要将输入的 ID 传递给远程数据源的 url。
我已经通过 hack 让它工作了,但我觉得我做了两次,有没有什么方法可以在不使用按键功能的情况下获取输入 ID?
我需要传递给 url 的输入 ID,因为 PHP 文件中有一些逻辑取决于正在使用的输入。
html
<input id="input1" class="selector" type="text">
js
$(".selector").keypress(function() {
var param2id = $(this).attr('id'); // this id needs to pass to the url
$(".selector").autocomplete({
minLength: 1,
max: 10,
source: "source.php?param2=" + param2id + "", // passed from the keypress
focus: function(event, ui) {
$(this).val(ui.item.value);
return false;
},
select: function(event, ui) {
$(this).val(ui.item.value);
return false;
}
});
});
它实际上有点复杂,因为自动完成不会引用它所设置的元素。所以你可以通过每个函数包装它们,这样你就不必使用 keypress
。这将仅设置一次引用。
$('.selector').each(function(i, el) {
param2id = $(el).attr("id");
$(el).autocomplete({
minLength: 1,
max: 10,
source: "source.php?param2=" + param2id + "",
focus: function(event, ui) {
$(this).val(ui.item.value);
return false;
},
select: function(event, ui) {
$(this).val(ui.item.value);
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/themes/smoothness/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"></script>
<input class="selector" id="input1">
我需要将输入的 ID 传递给远程数据源的 url。
我已经通过 hack 让它工作了,但我觉得我做了两次,有没有什么方法可以在不使用按键功能的情况下获取输入 ID?
我需要传递给 url 的输入 ID,因为 PHP 文件中有一些逻辑取决于正在使用的输入。
html
<input id="input1" class="selector" type="text">
js
$(".selector").keypress(function() {
var param2id = $(this).attr('id'); // this id needs to pass to the url
$(".selector").autocomplete({
minLength: 1,
max: 10,
source: "source.php?param2=" + param2id + "", // passed from the keypress
focus: function(event, ui) {
$(this).val(ui.item.value);
return false;
},
select: function(event, ui) {
$(this).val(ui.item.value);
return false;
}
});
});
它实际上有点复杂,因为自动完成不会引用它所设置的元素。所以你可以通过每个函数包装它们,这样你就不必使用 keypress
。这将仅设置一次引用。
$('.selector').each(function(i, el) {
param2id = $(el).attr("id");
$(el).autocomplete({
minLength: 1,
max: 10,
source: "source.php?param2=" + param2id + "",
focus: function(event, ui) {
$(this).val(ui.item.value);
return false;
},
select: function(event, ui) {
$(this).val(ui.item.value);
return false;
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/themes/smoothness/jquery-ui.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.3/jquery-ui.min.js"></script>
<input class="selector" id="input1">