为Bootstrap-select插件增加选项插图

0. 安装/引入 与使用

点击这里进入官方页,查看引入方法与基本使用.

1. 正事儿

项目需要,要在某页面的select项中加入品牌logo图片,其他页面中的选择框都使用的Bootstrap-select插件,查看源码后发现它只支持在<option/>标签中添加 'data-icon' 属性(下面代码中的icon变量):

var optionClass = this.className || '',
            inline = htmlEscape(this.style.cssText),
            text = $this.data('content') ? $this.data('content') : $this.html(),
            tokens = $this.data('tokens') ? $this.data('tokens') : null,
            subtext = typeof $this.data('subtext') !== 'undefined' ? '<small class="text-muted">' + $this.data('subtext') + '</small>' : '',
            icon = typeof $this.data('icon') !== 'undefined' ? '<span class="' + that.options.iconBase + ' ' + $this.data('icon') + '"></span> ' : '',
            $parent = $this.parent(),
            isOptgroup = $parent[0].tagName === 'OPTGROUP',
            isOptgroupDisabled = isOptgroup && $parent[0].disabled,
            isDisabled = this.disabled || isOptgroupDisabled,
            prevHiddenIndex;

然后在后面的代码中拼接html:

        if (icon !== '' && isDisabled) {
          icon = '<span>' + icon + '</span>';
        }
        if (!$this.data('content')) {
          // Prepend any icon and append any subtext to the main text.
          text = icon + img + '<span class="text">' + text + subtext + '</span>';
        }

要添加图片功能,于是添加一个 img变量用于拼接<img>标签,并拼接进text中:

        var optionClass = this.className || '',
            inline = htmlEscape(this.style.cssText),
            text = $this.data('content') ? $this.data('content') : $this.html(),
            tokens = $this.data('tokens') ? $this.data('tokens') : null,
            subtext = typeof $this.data('subtext') !== 'undefined' ? '<small class="text-muted">' + $this.data('subtext') + '</small>' : '',
            icon = typeof $this.data('icon') !== 'undefined' ? '<span class="' + that.options.iconBase + ' ' + $this.data('icon') + '"></span> ' : '',
            img = typeof $this.data('img') !== 'undefined' ? '<img class="my-logo" src="' + $this.data('img') + '"> ' : '', //添加img
            $parent = $this.parent(),
            isOptgroup = $parent[0].tagName === 'OPTGROUP',
            isOptgroupDisabled = isOptgroup && $parent[0].disabled,
            isDisabled = this.disabled || isOptgroupDisabled,
            prevHiddenIndex;

        if (icon !== '' && isDisabled) {
          icon = '<span>' + icon + '</span>';
        }

        if (!$this.data('content')) {
          // Prepend any icon and append any subtext to the main text.
          text = icon + img + '<span class="text">' + text + subtext + '</span>';  //拼接
        }

这样,只要在HTML中的<option/>中加入 'data-img' 标签即可:

<select class='selectpicker'>
    <option data-img="http://../123.jpg" value="val">Label</option>
</select>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值