• Jobs
  • About Us
  • professionals
    • Home
    • Jobs
    • Courses and challenges
  • business
    • Home
    • Post vacancy
    • Our process
    • Pricing
    • Assessments
    • Payroll
    • Blog
    • Sales
    • Salary Calculator

0

273
Views
jQuery: ¿cómo obtener el nombre de los datos?

Tengo muchos div con el atributo "valor de datos". Pero solo uno con el nombre de clase ".seleccionado". Necesito hacer selector con ambos. Datos + nombre de clase.

¿Cómo hacer un selector con atributo de datos y nombre de clase?

HTML

 <div data-value="x">Click Me!</div> <div data-value="y">Click Me!</div> <div class='selected' data-value="z">Click Me!</div> <div data-value="w">Click Me!</div>

jQuery

 alert( $("div[data-value] .selected").data('value') ); // this is wrong way...
about 3 years ago · Santiago Trujillo
3 answers
Answer question

0

Hay dos formas de obtener el atributo de data :

 $(".selected").attr('data-value'); // It works for all type of custom attribute

o

 $(".selected").data('value'); // This one is specially for data attribute
about 3 years ago · Santiago Trujillo Report

0

Puedes hacer eso con attr() de jQuery:

 alert($('div').attr('data-value'));

Pero, como habrá más de un div, mejor darle una clase a cada uno (para ser más específicos):

 <div class="clickable" data-value="x">Click Me!</div> <div class="clickable" id="second" data-value="y">Click Me!</div> <div class='selected clickable' data-value="z">Click Me!</div> <div class="clickable" data-value="w">Click Me!</div>

y el jQuery será:

 $('div.clickable').on('click', function(){ alert($(this).attr('data-value')); });

Violín aquí: https://jsfiddle.net/hpb5u62e/

about 3 years ago · Santiago Trujillo Report

0

verifique el ejemplo de trabajo. He agregado un evento de clic para el botón

 $(document).ready(function(){ $("button").click(function(){ alert( $(".selected").attr('data-value') ); }); });
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div data-value="x">Click Me!</div> <div data-value="y">Click Me!</div> <div class='selected' data-value="z">Click Me!</div> <div data-value="w">Click Me!</div> <button>Click me</button>

about 3 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Our process Sales
Legal
Terms and conditions Privacy policy
© 2025 PeakU Inc. All Rights Reserved.

Andres GPT

Recommend me some offers
I have an error