How to get, set and select elements with data attributes?

后端 未结 4 1443
臣服心动
臣服心动 2020-12-14 01:53

I\'m having some trouble with data-attributes, I can\'t get anything to work for some reason so I must be doing something wrong:

Set:

$(\'#element\')         


        
4条回答
  •  眼角桃花
    2020-12-14 02:48

    You are using ID selector so there is no need to use attribute selector, as data is a property and you are setting it using data method (not attr method) you cannot select the element using attribute selector, if you want to select the element only if it has data1 === 1 you can use the filter method:

    (function($){
        $(function(){
           // ...
           $('#element').filter(function() {
              return this.dataset.data1 == 1
              // return $(this).data('data1') == 1
           })
        })
    })(jQuery);
    

    dataset: Allows access, both in reading and writing mode, to all the custom data attributes (data-*) set on the element. It is a map of DOMString, one entry for each custom data attribute.

提交回复
热议问题