[英]Use html input data field attribute on bootstrap typeahead
I'm trying to get a data-field attribute to select what field of my "objects.json" will be used as source of my Bootstrap Typeahead input text, like: 我正在尝试获取数据字段属性,以选择将“ objects.json”的哪个字段用作我的Bootstrap Typeahead输入文本的源,例如:
form.html form.html
<input type="text" data-provide="typeahead" data-field="name">
form.js form.js
$("[data-provide=typeahead]").typeahead({
source: function(query, process) {
return $.get("/objects.json", {
query: query
}, function(data) {
return process($.map(data, function(o) {
return o[$(this).data('field')];
}));
});
}
});
objects.json objects.json
[{"id":1,"name":"lorem"},
{"id":2,"name":"ipsum"},
{"id":3,"name":"dolor"}]
The problem is the "$(this).data('field')" on Javascript isn't get the HTML data-field attribute. 问题是Javascript上的“ $(this).data('field')”没有获得HTML数据字段属性。
Thanks in advance! 提前致谢!
Not sure if this applies to you, but in my case, I figured that data-field
does not work. 不知道这是否适用于您,但就我而言,我认为
data-field
无效。 I tried to search online to see if " field " is a reserved word but couldn't find anything. 我试图在网上搜索以查看“ field ”是否为保留字,但找不到任何内容。 Anyway, changing the
data
attribute to anything else (eg: data-myfield
, data-fieldID
, etc.) worked for me. 无论如何,将
data
属性更改为其他任何属性(例如: data-myfield
, data-fieldID
等)对我来说都是有效的。
have you tried to use $(this).attr('data-field')? 您是否尝试过使用$(this).attr('data-field')? i also you may want to look here: http://api.jquery.com/attribute-equals-selector/ that may also be some of your problem, depending on wether you even get your initial element
我也可能要看一下这里: http : //api.jquery.com/attribute-equals-selector/这也可能是您遇到的一些问题,具体取决于您是否获得了初始元素
Try this: 尝试这个:
$("[data-provide=typeahead]").typeahead({
source: function(query, process) {
return $.get("/objects.json", {
query: query
}, function(data) {
return process($.map(data, function(o) {
return o[$(this).attr('data-field')]; //<-- Use attr()
}));
});
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.