将输入id传递到jquery ui自动完成中的url


Pass input id to url in jquery ui autocomplete

我需要将输入的id传递到远程数据源的url。

我已经通过黑客攻击实现了它,但我觉得我做了两次事情,有什么方法可以在不使用按键功能的情况下获得输入id吗?

我需要将输入id传递到url,因为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;
            }
        });

    });

它实际上有点复杂,因为自动完成不会引用它所设置的元素。所以你可以通过each函数包装它们,所以你不必使用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">