这是我构建下拉列表的方式(以haml):
#my_dropdown.ui.dropdown{ data: { path: objects_path } }
= f.hidden_field :my_id
%i.dropdown.icon
.default.text Text
.menu
- @collection.each do |object|
.item{ data: { value: object.id, text: object.name, color: object.color } }
= object.name
这工作得很好。我的.item
元素有额外的数据,例如.data('color')
. 我决定切换到 ajax 方法,而不是一次加载所有元素。
$.fn.api.settings.api =
'search objects': $('#my_dropdown').data('path') + '?q={query}'
$('#my_dropdown').dropdown
apiSettings:
action: 'search objects'
onChange: (value, text, selectedItem) ->
console.log selectedItem.data()
这是我返回的 JSON 的样子:
{
"success":true,
"results": [
{ "name":"Object #1", "value":1, "color":"blue" },
{ "name":"Object #2", "value":2, "color":"red" },
{ "name":"Object #3", "value":3, "color":"green" }
]
}
当我console.log selectedItem.data()
在下拉选择更改后执行以下操作时,我只看到:
{ value: 1 }
生成的 HTML 如下所示:
<div class="item" data-value="1">Object #1</div>
<div class="item" data-value="2">Object #2</div>
<div class="item" data-value="3">Object #3</div>
如何让项目包含自定义数据属性,例如data-color
在使用 Ajax 时?
我能够使用以下代码手动覆盖语义 UI 菜单模板:
$.fn.dropdown.settings.templates =
menu: (response, fields) ->
values = response[fields.values] or {}
html = ''
$.each values, (index, option) ->
extraData = ''
$.each fields.extraAttrs, (_j, attr) ->
if option[attr]
extraData += "data-#{attr}='" + option[attr] + "''"
maybeText = if option[fields.text] then 'data-text="' + option[fields.text] + '"' else ''
maybeDisabled = if option[fields.disabled] then 'disabled ' else ''
html += '<div class="' + maybeDisabled + 'item" data-value="' + option[fields.value] + '"' + extraData + maybeText + '>'
html += option[fields.name]
html += '</div>'
return
html
然后当我初始化我的下拉菜单时,我可以这样做:
$('#my_dropdown').dropdown
apiSettings:
action: 'search objects'
fields:
extraAttrs: ['color']
这允许我访问每个下拉项上的额外数据元素。如果有人有更好的方法来做到这一点,请告诉我。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句