Javascript获取嵌套元素值

时间:2015-10-19 10:52:38

标签: javascript jquery

我的html代码如下:

<div class="formContent">                       
    <label for="title">Data Collection Title:</label><p>Western Australia</p><br/>
    <label for="description">Description</label><p>Examples of ...</p><br/>
</div>

我如何访问这些值,例如西澳大利亚州和使用JavaScript的示例?

2 个答案:

答案 0 :(得分:0)

使用纯JavaScript,这很简单:

var p = document.querySelectorAll('.formContent p');
for (var i = 0, len = p.length; i < len; i++)
    console.log( p[i].textContent );

如果使用jQuery,逻辑是相同的:

$('.formContent p').each(function() {
    console.log( $(this).text() );
});

&#13;
&#13;
var p = document.querySelectorAll('.formContent p');
for (var i = 0, len = p.length; i < len; i++)
  console.log( p[i].textContent );
&#13;
<div class="formContent">                       
    <label for="title">Data Collection Title:</label><p>Western Australia</p><br/>
    <label for="description">Description</label><p>Examples of ...</p><br/>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

香草:

var txt = $('.formContent label[for="title"]').next("p").text();
console.log(txt);

jQuery的:

library(shiny)
data <- matrix(round(runif(5*3)),ncol=3)

ui <- shinyUI(fluidPage(
  fluidRow(
    column(6, h4("Randomly Selected Row [k]")),
    column(6, h4("Nex Row [k+1]"))
  ),
  fluidRow(
    column(6, textOutput("selRow")),
    column(6, textOutput("nxtRow"))
  ),
  fluidRow(
    column(8, textInput("guessStr","Gues row: ")),
    column(4, actionButton("guess","guess"))
  ),
  textOutput("guessRes")
))

server <- shinyServer(function(input, output, session) {
  # Make the current rownumber a reactive
  r.num <<- 0
  makeReactiveBinding('r.num')

  # If rownumber changes update UI
  observe({
    if(is.null(r.num)) return(NULL)
    output$selRow <- renderPrint({data[r.num,]})
    output$nxtRow <- renderPrint({data[r.num+1,]})
  })

  # Get a row number by random, can't select last row
  randomRow <- function(){
    r.num <<- sample(1:nrow(data)-1, 1)
  }

  # If user presses guess button
  observeEvent(input$guess, {
    # I convert to numerical but this can be modified to work with characters to
    input.str <- as.numeric(strsplit(input$guessStr,',')[[1]])

    msg <- sprintf("You guessed that the next row is: %s",input$guessStr)
    if( identical(data[r.num+1,], input.str)){
      msg <- paste(msg," , this was correct!")
    }
    else{
      msg <- paste(msg," , this was wrong")
    }
    output$guessRes <- renderPrint({msg})
  })

  # Initiate the guessing by randmozing a row
  randomRow()
})

shinyApp(ui = ui, server = server)