AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 79372888
Accepted
Dennis
Dennis
Asked: 2025-01-21 07:29:56 +0800 CST2025-01-21 07:29:56 +0800 CST 2025-01-21 07:29:56 +0800 CST

status de exibição div não alterado pelo javascript

  • 772

Há pouco tempo, postei uma pergunta semelhante a esta que tinha um erro de digitação causando confusão. Peço desculpas por isso, não serviu bem a nenhum de nós e já foi deletado. Fiz o meu melhor para garantir que este código esteja limpo e sem erros de digitação. Este código também mostra o problema descrito.

Esta questão representa melhor o problema que tenho: que uma div não está sendo mostrada quando sua propriedade display está definida como 'block'. O código reduzido é o seguinte:

function selectVidId(youtubeId, tableRowNbr, tableRowId, videoWidth, videoHeight) {
  const embedElement = document.getElementById('embedDiv');
  const videoElement = document.getElementById('videoDiv');

  let response = "<div id='muteYouTubeVideoPlayer'></div> \
    <script> \
      function onYouTubeIframeAPIReady() \
        {
        var player = new YT.Player('muteYouTubeVideoPlayer', \
            { videoId : 'f5JVDUI81nk' // YouTube Video ID    \
            , width   : 480          // Player width (in px) \
            , height  : 360         // Player height (in px) \
            , playerVars: \
              { autoplay       : 0  // Auto-play the video on load       \
              , controls       : 1  // Show pause/play buttons in player \
              , showinfo       : 1  // Show the video title              \
              , modestbranding : 1  // Hide the Youtube Logo             \
              , loop           : 0  // Don't run the video in a loop     \
              , fs             : 0  // Don't hide the full screen button \
              , cc_load_policy : 0  // Hide closed captions              \
              , iv_load_policy : 3  // Hide the Video Annotations        \
              , autohide       : 0  // Hide video controls when playing  \
              } // playerVars \
            , events: {} // events \
            } \
          ) ; // new .Player \
        } // function \
      // Written by @labnol \
    </script>";

  videoElement.style.display = 'none';
  embedElement.innerHTML = response;
  embedElement.style.display = 'block';
}
<!DOCTYPE html>
<html lang='en'>

<head>
  <title>Livestreams</title>
  <style>
  </style>
</head>
<script src="dbg.js">
</script>
</head>

<body>
  <div id='fullPageDiv' style='width: 100%; overflow:hidden;'>
    <div id='livestreamTable' style='width: 60%;float:left;'>
      <table border='1'>
        <thead>
          <tr>
            <th>Started</th>
            <th>Channel</th>
            <th>Songs noted</th>
            <th style='text-align:right;'>Duration</th>
            <th style='text-align:right;'>Dimensions</th>
            <th>Livestream Title</th>
          </tr>
        </thead>
        <tbody>
          <tr id='livestream_row_0'>
            <td>2021-12-04 07:15:08</td>
            <td style='text-align:left;'>Primary</td>
            <td style='text-align:right;'></td>
            <td style='text-align:right;'>1:04:54</td>
            <td style='text-align:right;' id='videoDimensions0'>1280x720*</td>
            <td><span onclick='selectVidId("f5JVDUI81nk", 0, "livestream_row_0", "1280", "720");'>Click-this-element</span></td>
          </tr>
        </tbody>
      </table>
    </div><!-- Livestream table -->
    <div id='videoDiv' style='display: none;'>
      <video id='idVideo' width="320" height="240" controls>
                <!-- <source src='replaceme.mp4' type='video/mp4'> -->
                Need top insert some video content here.
        </video>
    </div><!--videoDiv-->
    <div id='embedDiv' style='display: none;'>
      <p>Why, hello there!</p>
    </div><!-- embedDiv-->
  </div><!-- This is the "page" division (the whole page after the form) -->

</html>

O propósito não cumprido desta página é apresentar uma lista de itens e, quando um desses itens for clicado, um vídeo do YouTube associado será exibido no canto superior direito. Quando executo isso no depurador do Chrome, cada linha do código javascript é executada. No final, o valor embedElement.style.display é de fato definido como 'block', mas nada do embedDiv é exibido. (Eu inseri o texto bobo "Olá" apenas porque ele deveria aparecer mesmo se outras coisas fossem problemáticas.)

Novamente pergunto: qual é a coisa fundamental que estou esquecendo que faz com que essa div (aparentemente) não seja exibida?

Qual seria a abordagem correta para substituir o conteúdo de embedDiv de forma que o código necessário seja realmente executado?

javascript
  • 1 1 respostas
  • 50 Views

1 respostas

  • Voted
  1. Best Answer
    Barmar
    2025-01-21T08:06:26+08:002025-01-21T08:06:26+08:00

    Você está substituindo o div por um div vazio, então não há nada para exibir quando você altera o embedDiv.style.display.

    Livre-se da tarefa para emmedDiv.innerHTMLou coloque algum texto em resposta.

    function selectVidId(youtubeId, tableRowNbr, tableRowId, videoWidth, videoHeight) {
      const embedElement = document.getElementById('embedDiv');
      const videoElement = document.getElementById('videoDiv');
    
      let response = "<div id='muteYouTubeVideoPlayer'>This text will display</div>";
    
      videoElement.style.display = 'none';
      embedElement.innerHTML = response;
      embedElement.style.display = 'block';
    }
    <!DOCTYPE html>
    <html lang='en'>
    
    <head>
      <title>Livestreams</title>
      <style>
      </style>
    </head>
    <script src="dbg.js">
    </script>
    </head>
    
    <body>
      <div id='fullPageDiv' style='width: 100%; overflow:hidden;'>
        <div id='livestreamTable' style='width: 60%;float:left;'>
          <table border='1'>
            <thead>
              <tr>
                <th>Started</th>
                <th>Channel</th>
                <th>Songs noted</th>
                <th style='text-align:right;'>Duration</th>
                <th style='text-align:right;'>Dimensions</th>
                <th>Livestream Title</th>
              </tr>
            </thead>
            <tbody>
              <tr id='livestream_row_0'>
                <td>2021-12-04 07:15:08</td>
                <td style='text-align:left;'>Primary</td>
                <td style='text-align:right;'></td>
                <td style='text-align:right;'>1:04:54</td>
                <td style='text-align:right;' id='videoDimensions0'>1280x720*</td>
                <td><span onclick='selectVidId("f5JVDUI81nk", 0, "livestream_row_0", "1280", "720");'>Click-this-element</span></td>
              </tr>
            </tbody>
          </table>
        </div><!-- Livestream table -->
        <div id='videoDiv' style='display: none;'>
          <video id='idVideo' width="320" height="240" controls>
                    <!-- <source src='replaceme.mp4' type='video/mp4'> -->
                    Need top insert some video content here.
            </video>
        </div><!--videoDiv-->
        <div id='embedDiv' style='display: none;'>
          <p>Why, hello there!</p>
        </div><!-- embedDiv-->
      </div><!-- This is the "page" division (the whole page after the form) -->
    
    </html>

    • 1

relate perguntas

  • classificação de mesclagem não está funcionando - código Javascript: não é possível encontrar o erro mesmo após a depuração

  • método select.remove() funciona estranho [fechado]

  • Sempre um 401 res em useOpenWeather () - react-open-weather lib [duplicado]

  • O elemento de entrada não possui atributo somente leitura, mas os campos ainda não podem ser editados [fechado]

  • Como editar o raio do primeiro nó de um RadialTree D3.js?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve