来自“data-”的jQuery camel-case映射属性名称为“.data()”按键 [英] jQuery camel-case mapping from "data-" attribute names to ".data()" keys

查看:96
本文介绍了来自“data-”的jQuery camel-case映射属性名称为“.data()”按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您在元素上添加data-属性:

If you put a "data-" attribute on an element:

<div id='x' data-key='value'>

然后你可以通过jQuery.data()方法得到这个值:

then you can get the value via the jQuery ".data()" method:

alert($('#x').data('key')); // alerts "value"

该库使用一致的驼峰转换器来处理带有嵌入破折号的属性名称:

The library uses a consistent camel-case converter for attribute names with embedded dashes:

<div id='x' data-hello-world="hi">

alert($('#x').data("helloWorld"));

驼峰转换器是一个jQuery全局函数:

The camel-case converter is a jQuery "global" function:

alert($.camelCase("hello-world")); // alerts "helloWorld"

然而,当属性名称具有单个名称时,这一切都会失效破折号包围的字母:

However this all breaks down when the attribute name has a name with a single letter surrounded by dashes:

<div id='x' data-image-x-offset='50px'>

alert($('#x').data('imageXOffset')); // undefined

这有点奇怪,因为:

alert($.camelCase('image-x-offset')); // "imageXOffset"

那有什么不对?我认为它与用于执行其他方向的机制有关,将已经驼峰式的名称转换回虚线形式。但是我无法在代码中找到它。

So what's wrong? I think it has something to do with the mechanism used to go the other direction, converting an already camel-case name back into the dashed form. I can't pinpoint it in the code however.

在1.6.2中似乎和1.6.3中的相同。 (顺便说一下,image-x-offset形式可用于获取数据。)

Seems to be the same in 1.6.2 as in 1.6.3. (The form "image-x-offset" can be used to get the data, by the way.)

编辑—如果,对于给定的元素,您可以通过虚线形式访问尝试驼峰形式,然后它可以工作(这告诉我这肯定是 bug : - )

edit — if, for a given element, you access via the dashed form before attempting the camel-case form, then it works (and that tells me that this is definitely a bug :-)

推荐答案

你对了。问题似乎是他们用于从camelCase转换为虚线的正则表达式。

You're right. The issue seems to be with the regex they use for conversion from camelCase to dashed.

rmultiDash = /([a-z])([A-Z])/g;

... 此处使用

var name = "data-" + key.replace( rmultiDash, "$1-$2" ).toLowerCase();

...导致:

data-image-xoffset

...而不是:

data-image-x-offset

演示: http://jsfiddle.net/TLnaW/

因此,当您使用虚线版本时,当它查找属性时,它会找到它而不需要转换,然后将camelCase版本添加到元素数据在 jQuery.cache

So when you use the dashed version, when it looks for an attribute, it finds it with no need for a conversion, and then adds the camelCase version to the elements data in jQuery.cache.

随后的尝试将起作用,因为现在正确的camelCase存在,所以它不再试图将其作为属性,因此不再需要错误的正则表达式。

Subsequent attempts will then work because the correct camelCase is now there, so it no longer attempts to get it as an attribute, and therefore no longer needs the faulty regex.

这篇关于来自“data-”的jQuery camel-case映射属性名称为“.data()”按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆