You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Shiny应用全页面搜索栏及解决多contextId问题

解决Shiny应用中shinySearchbar多元素搜索的问题

你当前的代码仅指定单个按钮作为搜索范围,所以只能匹配到boton_google。要让搜索栏覆盖所有按钮,只需将所有目标元素放入一个统一的父容器,把容器ID作为contextId传入searchbar()即可。

修改后的完整代码

library(shiny)
library(bs4Dash)
library(stringr)
library(rintrojs)
library(shinyjs)
library(shinyWidgets)
library(fresh)
library(shinySearchbar)


caja_con_botones <- function(titulo, ..., botones) {
  div(
    h3(titulo, style = "color: steelblue;"),
    div(
      lapply(botones, function(boton) {
        div(boton, style = "margin-bottom: 5px;")
      })
    ),
    style = "text-align:center; border: 1px solid steelblue; padding: 10px;"
  )
}

# Función para crear botones
caja_elemento <- function(nombre, id, link, color) {
  color_class <- switch(color,
                        "rojo" = "btn-danger",
                        "azul" = "btn-primary",
                        "verde" = "btn-success",
                        "primary")  # Default to "primary" if color is not recognized

  tags$button(
    id = id,
    class = paste("btn", color_class),
    type = "button",
    onclick = paste0("window.open('", link, "', '_blank');"),
    nombre
  )
}

# Crear botones
boton_google <- caja_elemento("Abrir Google", "boton_google", "https://www.google.com/", "azul")
boton_facebook <- caja_elemento("Abrir Facebook", "boton_facebook", "https://www.facebook.com/", "red")

# UI de la aplicación Shiny
ui <- fluidPage(
  fluidRow(
    # 将contextId改为父容器的ID
    searchbar("buscador", contextId = "contenedor_botones")
  ),
  fluidRow(
    # 给所有按钮套一个带ID的父容器
    div(id = "contenedor_botones",
        caja_con_botones("Mis Enlaces",
                         botones = list(boton_google, boton_facebook))
    )
  )
 
)

server <- function(input, output) {

}

shinyApp(ui, server)

关键改动说明

  • 给包含所有按钮的区域添加了id="contenedor_botones"的父容器,明确搜索范围
  • 将searchbar()的contextId从单个按钮IDboton_google改为父容器IDcontenedor_botones,让搜索栏扫描容器内所有元素的文本内容

现在搜索"Abrir"时,会同时匹配两个按钮的文本,统计并标记两处匹配结果。

内容的提问来源于stack exchange,提问作者Raq

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.24 11:25:06