Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

113
Views
Manipular elemento al hacer clic en base al objetivo de datos

Así que estoy tratando de hacer un botón que cambie la visibilidad de un elemento div. Pero el enfoque sería obtener el valor del data-target del botón y manipular el elemento div correspondiente que tiene una id igual al valor del objetivo de datos. Estoy haciendo esto para poder reutilizar la función javascript en diferentes botones que tienen su propio elemento div correspondiente para alternar la visibilidad.

hasta ahora aquí está mi código html

 <header id="header"> <div class="header"> <div class="nav-container"> <a href="{{ route('home') }}" class="nav-brand"> <img src="{{ asset('logo_brandmark.png') }}" alt="logo_brandmark.png" class="nav-brandmark"><span class="nav-wordmark">{{ config('app.name', 'app name') }}</span> </a> <button class="btn btn-primary" data-target="navAuth" onclick="btnToggleVisibility(this)"><i class="fa fa-bars" aria-hidden="true"></i></button> </div> <div class="collapse" id="navAuth"> <a href="{{ route('login') }}" class="auth-link btn btn-primary">{{ __('Login') }}</a> <a href="{{ route('register') }}" class="auth-link btn btn-info">{{ __('Register') }}</a> </div> </div> </header>

y este es el javascript externo

 function btnToggleVisibility(obj) { var targetElement = obj.getAttribute('data-target'); targetElement.classList.toggle('show'); } window.btnToggleVisibility = btnToggleVisibility;

cuando hago clic en el botón, muestra este error ingrese la descripción de la imagen aquí

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

olvidaste el elemento que corresponde al valor de id

 function btnToggleVisibility(obj) { var targetElement = document.getElementById(obj.getAttribute('data-target')); targetElement.classList.toggle('show'); } window.btnToggleVisibility = btnToggleVisibility;
about 4 years ago · Juan Pablo Isaza Report

0

También puede leer valores de atributo data-* utilizando la propiedad de conjunto de dataset que está disponible en el elemento.

También podría reestructurar cómo está haciendo esto para que no esté definiendo o adjuntando el toggle directamente en los elementos usando el controlador de eventos onclick global. Podría hacer que los cambios futuros sean más simples para usted si las cosas están en una ubicación centralizada.

Por ejemplo, podría lograr su resultado de la siguiente manera:

 // the CSS class we'll toggle .hidden { visibility: hidden; }
 // the html <button type="button" class="toggler" data-target="#div-1">Show/Hide</button> <div class="hidden" id="div-1"> <p>This is the content that will be toggled</p> </div>
 document.addEventListener('DOMContentLoaded', (e) => { // define the function that will toggle the targets visibility using the .hidden class function toggleTargetVisibility(e) { // get all elements that match the target data-* attribute value // there may or may not be more than one element let div = document.querySelectorAll(e.dataset.target); // toggle the .hidden class for each found element div.forEach(function(el) { el.classList.toggle('hidden'); }) } // get all elements that will be responsible for triggering the toggle function let togglers = document.querySelectorAll('.toggler'); // attach the onclick event to each found toggler element togglers.forEach(function(toggler) { toggler.addEventListener('click', function(e) { toggleTargetVisibility(e.target); }); }) })
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!