Shiny中SelectizeInput实现选项部分内容加粗的方法
实现Shiny SelectizeInput选项中特定文本的加粗显示
可以实现这个需求,利用Selectize组件的自定义渲染功能,通过JavaScript代码修改选项的显示格式,把末尾带*的字符替换为加粗样式。以下是完整示例代码:
library(shiny) ui <- fluidPage( selectizeInput("select", label = "Choose one", choices = c("Option 1", "Option 2 *", "Option 3"), options = list( render = I("{\n\ item: function(item, escape) {\n\ return '<div>' + escape(item.text).replace(/\\*$/, '<strong>*</strong>') + '</div>';\n\ },\n\ option: function(item, escape) {\n\ return '<div>' + escape(item.text).replace(/\\*$/, '<strong>*</strong>') + '</div>';\n\ }\n\ }") )) ) server <- function(input, output, session) { # 可选:如果需要获取去除末尾*的选中值,可在此处理 observe({ cleaned_selection <- gsub("\\*$", "", input$select) print(cleaned_selection) }) } shinyApp(ui, server)
关键说明:
- 通过
selectizeInput的options参数传入Selectize的渲染配置,I()函数确保Shiny不转义这段JavaScript代码。 render.item负责处理选中后顶部显示的内容,render.option负责处理下拉列表中的选项内容,两者逻辑一致:先用escape(item.text)转义文本中的特殊字符(避免安全问题),再用正则表达式/\*$/匹配末尾的*,替换为<strong>*</strong>实现加粗。- 实际的输入值(
input$select)仍保留原始字符串(如"Option 2 *"),如果需要去除*,可以使用gsub函数处理。
内容的提问来源于stack exchange,提问作者mkranj
相关产品推荐
相关产品推荐

