将数据属性添加到selectize.js选项 [英] Add data-attribute to selectize.js options

查看:165
本文介绍了将数据属性添加到selectize.js选项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的项目使用selectize.js.但是我对数据属性有疑问.我想将数据属性添加到选择选项. 我的默认选择是这样的:

I am using selectize.js for my project. But I have problems with data-attributes. I want to add data-attributes to the select options. I have default select like this:

<option data-open-balance="false" selected="selected" value="1">PNP.SI.080416</option>

但是当我向该选择添加选择时,它变为:

But When I add selectize to this select, it becomes:

<div data-value="1" data-selectable="" class="selected">PNP.SI.080416</div>

我看到它的项目对象"仅获得值和文本.那么,如何向其item对象添加其他数据属性?

I see that its "item object" only get value, and text. So, how can I add other data-attributes to its item object?

推荐答案

我看过文档,他们说如果要向元素中添加自定义属性,则应使用dataAttr选项,默认情况下data-data.因此,在您的情况下,代码看起来像这样:

I've looked at docs and they say that if you want to add custom attributes to your elements, you should use dataAttr option, by default it data-data. So in your case code will look somethnig like this:

HTML

<select>
    <option data-data='{"openBalance": true}' selected="selected" value="1">PNP.SI.080416</option>
</select>

JS

在这里,我们提供了自定义渲染方法来绘制具有所需属性的options:

JS

Here we provide custom render method to draw options with attributes we need:

$('select').selectize({
    render: {
        option: function (data, escape) {
            return "<div data-open-balance='" + data.openBalance + "'>" + data.text + "</div>"
        }
    }
})

UDATE

Kyborek 所述,为了保护您的网站或Web应用程序免受

As Kyborek notes that in order to secure your site or web app from XSS, you should use escape method in render callback. Also use it if you want to display html tags in data.text. Updated example will look something like this:

$('select').selectize({
    render: {
        option: function (data, escape) {
            return "<div data-open-balance='" + escape(data.openBalance) + "'>" + escape(data.text) + "</div>"
        }
    }
})

这篇关于将数据属性添加到selectize.js选项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆