How to get the data-id attribute?

后端 未结 15 2442
青春惊慌失措
青春惊慌失措 2020-11-21 23:29

I\'m using the jQuery quicksand plugin. I need to get the data-id of the clicked item and pass it to a webservice. How do I get the data-id attribute? I\'m using the .

相关标签:
15条回答
  • 2020-11-21 23:48

    If we want to retrieve or update these attributes using existing, native JavaScript, then we can do so using the getAttribute and setAttribute methods as shown below:

    Through JavaScript

    <div id='strawberry-plant' data-fruit='12'></div>
    
    <script>
    // 'Getting' data-attributes using getAttribute
    var plant = document.getElementById('strawberry-plant');
    var fruitCount = plant.getAttribute('data-fruit'); // fruitCount = '12'
    
    // 'Setting' data-attributes using setAttribute
    plant.setAttribute('data-fruit','7'); // Pesky birds
    </script>
    

    Through jQuery

    // Fetching data
    var fruitCount = $(this).data('fruit');
    OR 
    // If you updated the value, you will need to use below code to fetch new value 
    // otherwise above gives the old value which is intially set.
    // And also above does not work in ***Firefox***, so use below code to fetch value
    var fruitCount = $(this).attr('data-fruit');
    
    // Assigning data
    $(this).attr('data-fruit','7');
    

    Read this documentation

    0 讨论(0)
  • 2020-11-21 23:48

    using jQuery:

      $( ".myClass" ).load(function() {
        var myId = $(this).data("id");
        $('.myClass').attr('id', myId);
      });
    
    0 讨论(0)
  • 2020-11-21 23:56

    I have a span. I want to take the value of attribute data-txt-lang, which is used defined.

    $(document).ready(function ()
    {
    <span class="txt-lang-btn" data-txt-lang="en">EN</span>
    alert($('.txt-lang-btn').attr('data-txt-lang'));
    });
    
    0 讨论(0)
提交回复
热议问题