Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

83
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda