问题描述:

I have one of the components label with the sample class tclick

<label class="btn btn-default tclick" data-tloc="value1" data-tkey="key1" >

<label class="btn btn-default tclick" data-tloc="value2" data-tkey="key2" >

<label class="btn btn-default tclick" data-tloc="value3" data-tkey="key3" >

Whenever click on any one component of label, class "checked" will be automatically added to label :

ex:

<label class="btn btn-default tclick checked" data-tloc="value1" data-tkey="key1" >

<label class="btn btn-default tclick checked" data-tloc="value2" data-tkey="key2" >

but i want get exactly data-tloc, data-tkey when label is click ?

i like code jquery and I need one solution ?

网友答案:

$('label.tclick').click(function() {
  $(this).addClass('checked');
  var tloc = $(this).data('tloc'),
      tkey = $(this).data('tkey');
  console.log(tloc, tkey);
});
.checked { color: red; }
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<label class="tclick" data-tloc="value1" data-tkey="key1">Label1</label>
<label class="tclick" data-tloc="value2" data-tkey="key2">Label2</label>
<label class="tclick" data-tloc="value3" data-tkey="key3">Label3</label>
网友答案:

Solution:

$('label.tclick').click(function(){
    var tloc = $(this).data('tloc'),
        tkey = $(this).data('tkey');

    $(this).addClass('checked');

    console.log('Tloc:' + tloc + ', Tkey: ' + tkey);
});
网友答案:

After 'checked' is automatically added and you just want the data attributes on click then try on change because if click executes before the checked class is added is(':checked') may not work:

$( "label.tclick" ).on('change', function() {
  if($(this).is(':checked')){
    console.log($(this).data('tloc'));
    console.log($(this).data('tkey'));
  }
});
相关阅读:
Top