Home > Web Front-end > JS Tutorial > Get custom attributes of data- using jQuery_jquery

Get custom attributes of data- using jQuery_jquery

WBOY
Release: 2016-05-16 15:33:07
Original
1568 people have browsed it

Stop talking nonsense and start with the code

jQuery.fn.dataset = function(attr, val) {
    // 获取数据集
    if (arguments.length == 0) {
      var dataset = {};
      jQuery(this).eq(0).each(function() {
        var attrs = this.attributes;
        for (var i = 0, l = attrs.length; i < l; i++) {
          var attr = attrs[i];
          if (/^data-/i.test(attr.name)) {
            dataset[decode(encode(attr.name.substring(5)))] = autobox(attr.value);
            if (decode(encode(attr.name.substring(5))) == "path") {
              dataset[decode(encode(attr.name.substring(5)))] = attr.value != null &#63; String(attr.value) : null;
            }
            if (decode(encode(attr.name.substring(5))) == "name") {
              dataset[decode(encode(attr.name.substring(5)))] = attr.value != null &#63; String(attr.value) : null;
            }
          }
        }
      });
      return dataset;
    }

    // 返回指定数据
    if (arguments.length == 1 && typeof attr != 'object') {
      if(encode(attr) == "data-path"){
        return this.attr(encode(attr));
      }
      return autobox(this.attr(encode(attr)));
    }

    // 设置数据集
    var dataset = attr;
    if (typeof attr != 'object') {
      dataset = {};
      dataset[attr] = String(val);
    }
    var tmp = {};
    jQuery.each(dataset, function(k, v) {
      tmp[encode(k)] = autobox(v);
    });
    return this.attr(tmp);
  };

Copy after login

By making components with jQuery, you can easily get the custom attributes of our data-, and you can also assign values ​​to the data- attributes.

Get:

$("div").dataset("name") //获取data-name的值
Copy after login

Assignment:

$("div").dataset("name","Tezml") //给data-name这个属性赋值为Tezml

Copy after login

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template