How to get the data-id attribute?

后端 未结 15 2441
青春惊慌失措
青春惊慌失措 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:31

    HTML

    <span id="spanTest" data-value="50">test</span>
    

    JS

    $(this).data().value;
    

    or

    $("span#spanTest").data().value;
    

    ANS : 50

    Works for me!

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

    The issue is you are not specifying the option or selected option of dropdown or list, Here is an example for dropdown, i am assuming a data attribute data-record.

    $('#select').on('change', function(){
            let element = $("#visiabletoID");
            element.val($(this).find(':selected').data('record'));
        });
    
    0 讨论(0)
  • 2020-11-21 23:34

    I use $.data - http://api.jquery.com/jquery.data/

    //Set value 7 to data-id 
    $.data(this, 'id', 7);
    
    //Get value from data-id
    alert( $(this).data("id") ); // => outputs 7
    
    0 讨论(0)
  • 2020-11-21 23:36
    var id = $(this).dataset.id
    

    works for me!

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

    For those looking to dynamically remove and re-enable the tooltip, you can use the dispose and enable methods. See https://getbootstrap.com/docs/4.0/components/tooltips/#tooltipdispose

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

    Important note. Keep in mind, that if you adjust the data- attribute dynamically via JavaScript it will NOT be reflected in the data() jQuery function. You have to adjust it via data() function as well.

    <a data-id="123">link</a>
    

    js:

    $(this).data("id") // returns 123
    $(this).attr("data-id", "321"); //change the attribute
    $(this).data("id") // STILL returns 123!!!
    $(this).data("id", "321")
    $(this).data("id") // NOW we have 321
    
    0 讨论(0)
提交回复
热议问题