通过数据属性和jquery实现可重用

Going reusable with data attributes and jquery

本文关键字:实现 jquery 数据属性      更新时间:2023-09-26

我的文本框前面附加了许多Bootstrap Type。我当时用那里的id来选择并附加typeahead。

样品

$("#SireTag").typeahead({
    source: function (query, process) {
        $.ajax({
            url: '/Bull/GetSireTag',
            type: 'POST',
            data: 'query=' + query,
            dataType: 'JSON',
                async: true,
                success: function (data) {
                    console.log(data);
                    process(data);
                }
            });
        }
    });

现在,我决定使用一个java脚本代码将type-ahead附加到我所有的文本框中,使它更可读、更简短。

<input data-typeahead-url="/Bull/GetSireTag" id="SireTag" name="SireTag" type="text" value="">

新的Javascript

 $('*[data-typeahead-url]')
        .each(function () {
            alert(this);
            $(this).typeahead({
                source: function (query, process) {
                    $.ajax({
                        url:  $(this).data("typeahead-url"),
                        type: 'POST',
                        data: 'query=' + query,
                        dataType: 'JSON',
                        async: true,
                        success: function (data) {
                            console.log(data);
                            process(data);
                        }
                    })
                }
            });
        });

但它不起作用,我不太精通java脚本,现在谁都错了。我试过开发人员的工具ajax请求没有发出。

$('*[data autocomplete url]')不会选择元素,因为您使用的是数据类型先行url。

您需要将ajax结果return发送到source,也不要使用alert()进行调试,而是使用console.log()

$('input[data-typeahead-url]').each(function () {
    $(this).typeahead({
        source: function (query, process) {
            return $.ajax({
                url:  $(this).data("typeahead-url"),
                type: 'POST',
                data: { query: query },
                dataType: 'json',
                async: true,
                success: function (resp) {
                    console.log(resp);
                    return process(resp);
                }
            });
        }
    });
});

希望能有所帮助。

$('*[data typeahead url]').each(函数(){

 var url = $(this).data("typeahead-url");
 $(this).typeahead({
     source: function (query, process) {
         $.ajax({
             url: url,
             type: 'POST',
             data: 'query=' + query,
             dataType: 'JSON',
             async: true,
             success: function (data) {
                 console.log(data);
                 process(data);
             }
         })
     }
 });

});

问题:代码发出ajax请求,但地址相同。诊断:我尝试了log($(this).data("typeahead-url");),它给出了所需的输出。解决方案:我创建并存储了Url,并将其用作ajax调用中的参数

var url = $(this).data("typeahead-url");

希望得到帮助。