jQuery .attr() 似乎区分大小写

标签 jquery case-sensitive attr

我有一个带有一些自定义属性的 select 元素,我用它来动态验证它并显示适当的消息。属性名称采用驼峰式命名,如下所示

<select validationMessage="Must select something" ... >...

问题是在早于 1.6 的 jQuery 版本中 .attr() 似乎区分大小写。更有问题的是,它不会获取原始大小写的属性。这在 Chrome 中的 Firefox 中工作方式相同,但在 Internet Explorer 中工作方式与预期相同(应不区分大小写)。同样有趣的是,任何外壳(除了原始外壳)都可以工作。

这是一个JSFiddle example这个问题。您可以更改左侧的 jQuery lib 版本,然后单击“运行”以检查它与其他版本的配合情况。

我该如何缓解这个问题?

最佳答案

jQuery 改变了 attr() 在 1.6 中的工作方式。在此版本之前,attr() 主要直接映射到属性 under the hood ——不是人们想象的那样的属性。由于 DOM 属性名称通常是单个单词,因此 jQuery 将传递的大多数字符串转换为小写,并对少数驼峰式命名的属性名称进行了异常(exception)处理。 jQuery 这样做的原因是为了处理浏览器的不一致以及 getAttribute()setAttribute() 中的错误。

As of jQuery 1.6, the .attr() method returns undefined for attributes that have not been set. In addition, .attr() should not be used on plain objects, arrays, the window, or the document. To retrieve and change DOM properties, use the .prop() method. source

在 1.6 中,attr() 映射到 getAttribute() under the hood ,以及新的prop()方法检索属性值。

The difference between attributes and properties can be important in specific situations. Before jQuery 1.6, the .attr() method sometimes took property values into account when retrieving some attributes, which could cause inconsistent behavior. As of jQuery 1.6, the .prop() method provides a way to explicitly retrieve property values, while .attr() only retrieves attributes. source

关于jQuery .attr() 似乎区分大小写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6042694/

相关文章:

MySQL SELECT DISTINCT 应​​该区分大小写吗?

r - 当 ignore.case = TRUE 时,gsubfn 函数未提供所需的输出

jquery - 带有全宽图像的 Bootstrap 导航栏附加

javascript - 如何获取类属性值的一部分?

jquery - 无法同时设置表格高度和 tr

linux - Magento 模块适用于 OS X 而不是 Linux

android - 如何将文档添加到自定义属性?

jquery - 如何从 div id 创建 json 对象或数组?

jquery - 获取鼠标悬停的元素的属性

javascript - Jquery 数据表 : Filter/Search based on select box outside the table