Skip to main content
 首页 » 编程设计

jquery之select2 组件中所选元素的工具提示

2026年07月28日5telwanggs

在我的项目中,我使用 select2 组件。对于我选择的元素,我添加了图标和描述。代码是这样的:

function format(profile_opt) { 
        return profile_opt.text + "<br><span class=\"description_select2\"><i>" + $(profile_opt.element).attr('title') + "</i></span><br>" + 
        ($(profile_opt.element).attr('start').length==0?'':('from: <b>' + $(profile_opt.element).attr('start') + '</b>')) + ($(profile_opt.element).attr('end').length==0?'':(' to: <b>' + $(profile_opt.element).attr('end') + '</b>')) +  
        " <a href=\"#\" onclick=javascript:showUrlInDialogWithOptionId(\"<%=request.getContextPath()%>/assignments_date_set.jsp\",\"" + profile_opt.id + "\",\"" + $(profile_opt.element).attr('start') + "\",\"" + $(profile_opt.element).attr('end') + "\")>" + 
        "<img src=\"images/icons/small/grey/clock.png\" title=\"Set start and end assignment dates\" alt=\"Set start and end assignment dates\" class=\"clock\" id=\"clock\" width=\"20px\" height=\"20px\"></a>"; 
    } 
 
    function format2(profile_opt){ 
        return profile_opt.text +"<br><span class=\"description_select2\"><i>" + $(profile_opt.element).attr('title') + "</i></span>"; 
    } 
 
    $('#selected_profiles').select2({ allowSelectAllNone: true, closeOnSelect:false, width: '600px', placeholder: 'Click to select',  
        formatResult: format2, 
        formatSelection: format, 
        escapeMarkup: function(m) { return m; } 
        }); 

我的问题是:如何将工具提示设置为格式选项元素的唯一子字符串。我的意思是我只需要工具提示的开头,而不需要内部包含 html 的整个语法。预先感谢您的帮助。

请您参考如下方法:

在 select2 构造函数中添加这 2 个参数:

formatResult: format, 
formatSelection: format 

然后在 select2 构造函数外部定义 format 函数,如下所示:

function format(item) { 
    var originalText = item.text; 
    return "<div title ='" + originalText + "'>" + originalText + "</div>"; 
} 

原帖为here