简体   繁体   English

rails和html数据属性:使用短划线( - )或下划线(_)?

[英]rails and html data attributes: use dash(-) or underscore(_)?

Lately, I'm facing problems with HTML custom data attributes in my rails application. 最近,我在rails应用程序中遇到HTML自定义数据属性的问题。 I user the following pattern in order to add some data attributes to the html tags and use them later in my javascript(jQuery) code: 我使用以下模式,以便将一些数据属性添加到html标记,并在稍后的javascript(jQuery)代码中使用它们:

= %a.name{ href: "url.com", data: {first_name: "ben", last_name: "amsalem} }

In the javascript code I access those attributes: 在javascript代码中,我访问这些属性:

alert($(".name").data("first_name") + " " + $(".name").data("last_name"));

In my development environment it goes well and I get the expected result (the same is true for my production environment in the past), but in my current production version I get "undefined" values. 在我的开发环境中,它很顺利,我得到了预期的结果(过去我的生产环境也是如此),但在我当前的生产版本中,我得到了“未定义”的值。 I checked the HTML source of the page and I saw that I now have something like: 我检查了页面的HTML源代码,我看到我现在有类似的东西:

<a class="name" href="url.com" data-first-name="ben" data-last-name="amsalem" />

Instead of: 代替:

<a class="name" href="url.com" data-first_name="ben" data-last_name="amsalem" />

Why does it happen? 为什么会这样? What causes the change? 是什么导致了变化?

It's perfectly normal, data: { first_name: "ben" } is supposed to produce data-first-name="ben" . 这是完全正常的, data: { first_name: "ben" }应该生成data-first-name="ben"

The best way you would access this attribute is with .data("firstName") , but .data("first-name") would also work. 访问此属性的最佳方法是使用.data("firstName") ,但.data("first-name")也可以。

I take it that you are using HAML. 我认为你使用的是HAML。 Hypernation comes as default since 4.0. 自4.0以来,Hypernation是默认的。 Set hyphenate_data_attrs to false to turn this off. hyphenate_data_attrs设置为false可将其关闭。

Documentation: http://haml.info/docs/yardoc/Haml/Options.html#hyphenate_data_attrs-instance_method 文档: http//haml.info/docs/yardoc/Haml/Options.html#hyphenate_data_attrs-instance_method

Original github pull discussion: https://github.com/haml/haml/pull/488 原始github拉讨论: https//github.com/haml/haml/pull/488

经过测试我做了:似乎在开发中我在版本3.2.9中有宝石,在生产中它是3.2.12 - 在这些版本之间修复了错误的行为(转换为<a date-last_name/> )我的开发版本我可以看到变化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM