Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

93
Visualizações
Dynamically Updating Image SRC using ES6

I have global JavaScript variable that is defined in PHP for use in a WordPress Block.

When the page initially loads, the "stars" image appears as expected. When a change event is fired, a 404 error appears in the console with "https://site.dev/img/var_set_in_php.imageSunset" as the URL instead of "https://site.dev/img/sunset.jpg".

How can this be updated to pull in the value that is set in PHP? I'm new to ES6, so hoping it's just something simple that I'm missing.

wp_localize_script(
    'image-js',
    'var_set_in_php', // Array containing dynamic data for a JS Global.
    array(
        'imageStars' => '/img/stars.jpg',
        'imageSunset' => '/img/sunset.jpg',
    )
);
function onChangeFunction(name) {
    // name is set to "Sunset"
    document.getElementById('image').src = `var_set_in_php.image${name}`;
}
<img src={var_set_in_php.imageStars} id="image" />
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

I think you have a

var var_set_in_php = {
 'imageStars' :'/img/stars.jpg', 
 'imageSunset' : '/img/sunset.jpg'
} 

and if you do, you need this to access the object with a compound variable

document.getElementById('image').src = var_set_in_php[`image${name}`];
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda