get data attribute value onclick link / button

2020-08-20 08:21发布

<span class="btn btn-block btn-inverse btn-icon glyphicons home" id="changeb" data-datac="daily"><i></i>Daily</span>
            <span class="btn btn-block btn-inverse btn-icon glyphicons home" id="changeb" data-datac="1week"><i></i>1 Week</span>
            <span class="btn btn-block btn-inverse btn-icon glyphicons home" id="changeb" data-datac="monthly"><i></i>Month</span>
            <span class="btn btn-block btn-inverse btn-icon glyphicons home" id="changeb" data-datac="3Month"><i></i>3 Month</span>

the jquery is

$('#changeb').click(function() {

        var d = $(this).data('datac');      
        alert(d);   
} );

I need to get the data-datac value on click event ,

标签: jquery html
6条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-08-20 08:34

You can't set all the elements a unique id. That's why it's happening only for the first element.

查看更多
小情绪 Triste *
3楼-- · 2020-08-20 08:35

Its Simple....

 var data_value = $(this).attr("data-datac");
查看更多
Ridiculous、
4楼-- · 2020-08-20 08:38

You can get attribute values of an element using the attr in jquery like

$('.home').on('click', function() {

    var d = $(this).attr('data-datac');      
    alert(d);   
});

F.Y.I

If you will use id's as selector you can only get one element while on a class you can get reference all the elements containing that class

查看更多
家丑人穷心不美
5楼-- · 2020-08-20 08:47

Use a unique id for each element

var d=$(this).attr('data-datac');
查看更多
ら.Afraid
6楼-- · 2020-08-20 08:54

Your code is fine you have same id for more then one element which is not valid. The event will be binded to first element with given id in the DOM. Use common class instead of id to bind the event. You can use class selector to bind the event.

Live Demo

$('.btn').click(function() {
      var d = $(this).data('datac');      
      alert(d);   
});
查看更多
虎瘦雄心在
7楼-- · 2020-08-20 08:59

This should do the trick:

var d = $(this).attr("data-datac");

Also, you need to change your HTML to give each element a seperate id. But it can be a tedious task to bind click events for a number of different ids. So i'd bind it to a seperate class. For example:

HTML

<span class="btn btn-block btn-inverse btn-icon glyphicons home dateChanger" id="changeb1" data-datac="daily"><i></i>Daily</span>
<span class="btn btn-block btn-inverse btn-icon glyphicons home dateChanger" id="changeb2" data-datac="1week"><i></i>1 Week</span>
<span class="btn btn-block btn-inverse btn-icon glyphicons home dateChanger" id="changeb3" data-datac="monthly"><i></i>Month</span>
<span class="btn btn-block btn-inverse btn-icon glyphicons home dateChanger" id="changeb4" data-datac="3Month"><i></i>3 Month</span>

Javascript

$(".dateChanger").click(function () {
    var d = $(this).attr("data-datac");
    alert(d);
});
查看更多
登录 后发表回答