简体   繁体   中英

JQuery attr() and Data() Returning undefined

This question has already been asked but no answer solved my problem don't know why below is the image of my code +

 window.onload = function() { $('button').click(deletingTheCar); } function deletingTheCar() { // alert($(this).data('id')); var my = $(this).data('data-items'); alert(my); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button data-items="yes got it" id="osama">Hi</button> 

我的代码的屏幕截图

Since you want to get data-* attributes the best method is .data() , and the .data() doesn't need the first part data- to be passed as parameter, so just replace :

$(this).data('data-items');
______________^^^^ //You have extra 'data' here

By :

$(this).data('items');

Working sample:

 window.onload = function() { $('button').click(deletingTheCar); } function deletingTheCar() { console.log( $(this).data('items') ); } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <button data-items="yes got it" id="osama">Hi</button> 

Update var my = $(this).data('data-items'); to

var my = $(this).data('items');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM