认识data-xxx 的属性

 认识data-xxx 的属性

如, 在bootstrap之data-toggle="table", 不加这个属性,就不能实现框架自带的js效果.

1.它属于 HTML5 的 data-* attribute 知识范畴

2. 在jQuery 1.6中,针对属性字面包含内嵌破折号的情况进行了更改,以符合W3C HTML5规范。

The treatment of attributes with embedded dashes was changed in jQuery 1.6 to conform to the W3C HTML5 specification.

1.1 进一步理解

当使用.data()获取值时,jQuery会首先尝试将获取的字符串值转化成JS类型,请参考

 jQuery中data函数源码

function dataAttr(elem, key, data) {
    // If nothing was found internally, try to fetch any 
    // data from the HTML5 data-* attribute 
    if (data === undefined && elem.nodeType === 1) {
        // rmultiDash = /([A-Z])/g 
        var name = "data-" + key.replace(rmultiDash, "-$1").toLowerCase();
        data = elem.getAttribute(name);
        if (typeof data === "string") {
            try {
                /*.data(key)方法尝试将获取的值转化成JS类型,包括布尔值,null,数字,对象,数组*/
                data = data === "true" ? true :
                data === "false" ? false :
                data === "null" ? null :
                // Only convert to a number if it doesn't change the string 
                +data + "" === data ? +data :
                /*rbrace = /(?:{[sS]*}|[[sS]*])$/,*/
                rbrace.test(data) ? jQuery.parseJSON(data) :
                data;
            } catch (e) { }
            // Make sure we set the data so it isn't changed later 
            jQuery.data(elem, key, data);
        } else {
            data = undefined;
        }
    }
    return data;
}
原文地址:https://www.cnblogs.com/zhuji/p/7146653.html