【问题标题】:When any tabs are refreshed, the page is automatically navigating to first tab刷新任何选项卡时,页面会自动导航到第一个选项卡
【发布时间】:2020-03-22 07:15:58
【问题描述】:

在下面的应用程序中,只要用户既不在 tab2 也不在 tab3 中并单击刷新,页面就会转到 tab1。我们能否避免这种情况并确保页面保持在相应的标签后刷新:slight_smile:是否有可能实现请指导我。

library(shiny)
ui <- fluidPage(
  tabsetPanel(
    id="inTabset",
    tabPanel("Tab 1",actionButton("switch_tab", "Go to the third tab")
    ),
    tabPanel("Tab 2", "there!"),
    tabPanel("Tab 3", "there!"))

)

server <- function(input, output, session) {

  observeEvent(input$switch_tab, {
    updateTabsetPanel(session, "inTabset",selected = "Tab 3")
  })

}
shinyApp(ui = ui, server = server)

【问题讨论】:

    标签: html css r shiny


    【解决方案1】:

    您需要保持状态,Shiny 对此有 a bookmark system,但在您的情况下,您可能希望拥有一个更不可见的机制。

    Cookie.js JavaScript library 添加到您的 Shiny 应用中,如下所示:

     tags$head(tags$script(src="https://cdnjs.cloudflare.com/ajax/libs/js-cookie/2.2.1/js.cookie.min.js")),
            tags$head(tags$script(src="app.js")),
            tabsetPanel(
                id="inTabset",
                tabPanel("Tab 1",actionButton("switch_tab", "Go to the third tab")),
                tabPanel("Tab 2", "there!"),
                tabPanel("Tab 3", "there!")),
    

    并在 Shiny 根目录的 www-directory 中创建一个 app.js 文件,内容如下:

    $(document).ready(function(){
       $("a[data-toggle='tab']").click(function(){
         const tabId = $(this).data("value");
         Cookies.set('tabId', tabId);
       })
       const cookieTabId = Cookies.get("tabId");
       if(cookieTabId){
         console.log(`Restoring tab '${cookieTabId}'`); 
         $(`a[data-value='${cookieTabId}']`).tab('show');
       }
     })
    

    上述JS中最难的部分是jQuery选择器和show()方法from Bootstrap

    您还可以将选定的选项卡值传输到服务器并将每个用户的会话值保存在数据存储中。它将在用户浏览器之外创建状态持久性。

    The solution can be downloaded from here.

    【讨论】:

    • 谢谢。想和你确认一下。除了创建 app.js 文件之外没有其他选择。我认为这可能只是一行代码?我不是这方面的专家。但是想和你确认一下
    • 您也可以内联添加 JS 代码,但如果您这样做,特殊字符(如 '>' 和引号)会出现一些烦人的问题。
    • 我尝试使用代码创建 app.js。标签仍将转到第一个标签:)
    猜你喜欢
    • 2021-02-15
    • 1970-01-01
    • 2014-12-31
    • 1970-01-01
    • 2020-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多