【问题标题】:Is there way to wrap results in Select2 in additional markup?有没有办法将 Select2 中的结果包装在附加标记中?
【发布时间】:2013-03-20 15:29:44
【问题描述】:

我一直在将 Select2 用于我的项目并取得了巨大成功。

我想知道是否有人知道对下拉标记进行重大修改的最佳方法。

例如,我想在结果底部添加一个输入字段和一个按钮。

对于 select2 来说,这似乎是一项可行的任务吗?或者它是一个错误的工具?目前我正在使用内部开发的插件,但它并不可靠且速度慢。

【问题讨论】:

  • 文本框的用途是什么?用于过滤或收集额外信息?
  • "Select a Course" 用于过滤,它是实际的select 字段
  • “输入您的课程编号”用于将项目添加到选择列表中

标签: javascript jquery jquery-select2


【解决方案1】:

开启选项:

<style>
#s2id_test
{
    width: 200px;
}
.addedDiv
{
    padding-left: 10px;
    padding-right: 10px;
}
.addedDiv input
{
    display: inline-block;
    width: 120px;
}
.addedDiv button
{
    display: inline-block;
    width: 40px;
}
</style>



<body>
<select id="test">
    <option value="1">Test 1</option>
    <option value="2">Test 2</option>
    <option value="3">Test 3</option>
    <option value="4">Test 4</option>
    <option value="5">Test 5</option>
</select>
<script>
(function ($) {

/**
* @function
* @property {object} jQuery plugin which runs handler function once specified element is inserted into the DOM
* @param {function} handler A function to execute at the time when the element is inserted
* @param {bool} shouldRunHandlerOnce Optional: if true, handler is unbound after its first invocation
* @example $(selector).waitUntilExists(function);
* https://gist.github.com/buu700/4200601
*/

$.fn.waitUntilExists    = function (handler, shouldRunHandlerOnce, isChild) {
    var found       = 'found';
    var $this       = $(this.selector);
    var $elements   = $this.not(function () { return $(this).data(found); }).each(handler).data(found, true);

    if (!isChild)
    {
        (window.waitUntilExists_Intervals = window.waitUntilExists_Intervals || {})[this.selector] =
            window.setInterval(function () { $this.waitUntilExists(handler, shouldRunHandlerOnce, true); }, 100)
        ;
    }
    else if (shouldRunHandlerOnce && $elements.length)
    {
        window.clearInterval(window.waitUntilExists_Intervals[this.selector]);
    }

    return $this;
}

}(jQuery));
$(document).ready(function(){
    $('#test').select2();

    $('#test').on("open", function() {
        if (!$('.addedDiv',$('.select2-drop-active')).is('*'))
        {
           $('.select2-drop-active').waitUntilExists(function(){$('.select2-drop-active').append('<div class="addedDiv"><input type="text"><button onclick="add(this)">Add</button></div>')});
        }
    });
 });
 function add(btn)
 {
    if($(btn).prev().is('input'))
    {
        $('#test').append('<option value="'+$($(btn).prev()).val()+'">'+$($(btn).prev()).val()+'</option>');
        $('#test').select2('close');
        $('#test').select2('open');
    }
 }
</script>

测试win32宽度:chrome、firefox、IE

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-12-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多