我的问题涉及观察 shinyBS 中 bsCollapsePanel 中标题的切换和取消切换事件。
让我们以以下应用为例:
library(shiny)
library(shinyBS)
server = function(input, output, session) {
observeEvent(input$p1Button, ({
updateCollapse(session, "collapseExample", open = "Panel 1")
}))
observeEvent(input$styleSelect, ({
updateCollapse(session, "collapseExample", style = list("Panel 1" = input$styleSelect))
}))
output$randomNumber <- reactive(paste0('some random number'))
}
ui = fluidPage(
sidebarLayout(
sidebarPanel(HTML("This button will open Panel 1 using <code>updateCollapse</code>."),
actionButton("p1Button", "Push Me!"),
selectInput("styleSelect", "Select style for Panel 1",
c("default", "primary", "danger", "warning", "info", "success"))
),
mainPanel(
bsCollapse(id = "collapseExample", open = "Panel 2",
bsCollapsePanel("Panel 1", "This is a panel with just text ",
"and has the default style. You can change the style in ",
"the sidebar.", style = "info")
),
verbatimTextOutput('randomNumber')
)
)
)
app = shinyApp(ui = ui, server = server)
我希望应用能够在每次打开 bsCollapsePanel
时在 verbatimTextOutput('randomNumber')
字段中打印一个随机数(使用 R shiny react 性)单击 Panel 1
标题。
我在想也许可以使用 shinyjs
包,但没有找到这两个包一起使用的很多例子。
最佳答案
好吧,Mike Wise 比我快 :) 如果出于某种原因我的解决方案也有帮助,请告诉我,否则我会删除它。
library(shiny)
library(shinyjs)
library(shinyBS)
ui = fluidPage(
useShinyjs(),
sidebarLayout(
sidebarPanel(HTML("This button will open Panel1 using <code>updateCollapse</code>."),
actionButton("p1Button", "Push Me!"),
selectInput("styleSelect", "Select style for Panel1",
c("default", "primary", "danger", "warning", "info", "success"))
),
mainPanel(
bsCollapse(id = "collapseExample", open = "Panel 2",
bsCollapsePanel("Panel1", "This is a panel with just text ",
"and has the default style. You can change the style in ",
"the sidebar.", style = "info", id = "me23")
),
verbatimTextOutput('randomNumber')
)
)
)
server = function(input, output, session) {
observeEvent(input$p1Button, ({
updateCollapse(session, "collapseExample", open = "Panel1")
}))
observeEvent(input$styleSelect, ({
updateCollapse(session, "collapseExample", style = list("Panel1" = input$styleSelect))
}))
observe({
runjs("function getAllElementsWithAttribute(attribute){
var matchingElements = [];
var allElements = document.getElementsByTagName('*');
for (var i = 0, n = allElements.length; i < n; i++)
{
if (allElements[i].getAttribute(attribute) !== null)
{
// Element exists with attribute. Add to array.
matchingElements.push(allElements[i]);
}
}
return matchingElements;
};
ahref = getAllElementsWithAttribute('data-toggle');
ahref[0].onclick = function() {
var nmbr = Math.random();
Shiny.onInputChange('randomNumber', nmbr);
};
")
})
output$randomNumber <- reactive(paste0(input$randomNumber))
}
shinyApp(ui = ui, server = server)
您可以在此处找到 Javascript 代码: Get elements by attribute when querySelectorAll is not available without using libraries?
关于javascript - shinyBS 观察 bsCollapsePanel 的切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43502731/